I'm trying to use ctypes for passing a bidimensional array and an unidimensional array to a C function from my python code then this function return an unidimensional array to my python terminal.
1-I need to pass the array from python, as you will see below (how i tried to do).
2-Probably i don't set up argument types and return types correctly. I've been searching a lot but nothing solve my problems.
My C code named Thomas_PYTHON_DLL.c:
#include"stdio.h"
#include"stdlib.h"
#include"Thomas.h"
EXPORT double* Thomas(int dimension, double MatrizTridiagonal[dimension]
[dimension],double vec_b[dimension]){
double* Thomas(int dimension, double MatrizTridiagonal[dimension]
[dimension],double vec_b[dimension]){
double a[dimension];
double b[dimension];
double c[dimension];
double resp[dimension];
double *solution;
solution=(double *) malloc(dimension*sizeof(double));
for(int i=0;i<dimension;i++){resp[i]=vec_b[i];}
for(int i=0;i<dimension;i++){
if(i==0){a[i]=0.0;}
else{
a[i]=MatrizTridiagonal[i][i-1];
}
}
for(int i=0;i<dimension;i++){
b[i]=MatrizTridiagonal[i][i];
}
for(int i=0;i<dimension;i++){
if(i==dimension-1){c[dimension-1]=0.0;}
else{
c[i]=MatrizTridiagonal[i][i+1];
}
}
for(int i=0;i<dimension;i++){
if(i==0){
c[i]=c[i]/b[i];
resp[i]=resp[i]/b[i];
}
else{
c[i]=c[i]/(b[i]-c[i-1]*a[i]);
resp[i]=(resp[i]-a[i]*resp[i-1])/(b[i]-a[i]*c[i-1]);
}
}
for(int i=dimension-1;i>=0;i--){
if(i==dimension-1){
solution[i]=resp[i];
}
else{
solution[i]=resp[i]-c[i]*solution[i+1];
}
}
for(int i=0;i<dimension;i++){printf("x%d=|%0.2f|
",i,solution[i]);}
return solution;
//free(solution);
}
}
My C code named Thomas.h:
#define EXPORT __declspec(dllexport)
EXPORT double* Thomas(int dimension, double MatrizTridiagonal[dimension]
[dimension],double vec_b[dimension]);
And finally my Python code, named Thomas_Python.py:
from ctypes import *
x=(c_double*5)
Tridiagonal = cdll.LoadLibrary('Thomas_dll.dll')
Tridiagonal.Thomas.restype=POINTER(x)
Tridiagonal.Thomas.argtypes=[c_int,((c_double*5)*5),(c_double*5)]
#arrays that i want to pass to C code
a=((c_double*5)*5)((2,-1,0,0,0),(-1,2,-1,0,0),(0,-1,2,-1,0),(0,0,-1,2,-1),
(0,0,0,-1,2))
b=(c_double*5)(4,2,2,2,4)
r=Tridiagonal.Thomas(5,a,b)
print(r[2])
In the code above, i expected to print the value of the array r in the position "2", but the print show me:
<__main__.c_double_Array_5 object at 0x03A77350>
A great help would be beyond knowing how to read array values, getting the entire array as a list. Thank you so much for all your help and time, and I apologize for my English.
See Question&Answers more detail:
os