I want to use C to deal with some computations. For example, I have a C function of adding two matrix:
// mat_add.c
#include <stdlib.h>
void matAdd(int ROW, int COL, int x[][COL], int y[][COL], int z[][COL]){
int i, j;
for (i = 0; i < ROW; i++){
for (j = 0; j < COL; j++){
z[i][j] = x[i][j] + y[j][j];
}
}
}
Then I compiled it into .so file:
gcc -shared -fPIC mat_add.c -o mat_add.so
And in python:
# mat_add_test.py
import ctypes
import numpy as np
def cfunc(x, y):
nrow, ncol = x.shape
objdll = ctypes.CDLL('./mat_add.so')
func = objdll.matAdd
func.argtypes = [
ctypes.c_int,
ctypes.c_int,
np.ctypeslib.ndpointer(dtype=np.int, ndim=2, shape=(nrow, ncol)),
np.ctypeslib.ndpointer(dtype=np.int, ndim=2, shape=(nrow, ncol)),
np.ctypeslib.ndpointer(dtype=np.int, ndim=2, shape=(nrow, ncol))
]
func_restype = None
z = np.empty_like(x)
func(nrow, ncol, x, y, z)
return z
if __name__ == '__main__':
x = np.array([[1, 2], [3, 4]], dtype=np.int)
y = np.array([[2, 2], [5, 6]], dtype=np.int)
z = cfunc(x, y)
print(z)
print('end')
Executed this python file, I obtained:
$ python mat_add_test.py
[[ 3 4]
[8386863780988286322 7813586346238636153]]
end
The first row of return matrix is correct, but the second row is wrong. I guess that I don't successfully update the value in z, but I have no idea where the problem is.
Can anyone help? Very thanks!
long. Probably there is some correct procedure with an appropriatetypedef- I am not suggesting hard-codinglongbut it suffices to demonstrate the point.y[j][j]should bey[i][j]x.dtypereportsdtype('int64')inttolong, and it works! I forget that np.int is difference to int in c. Very thanks!printf("i=%d j=%d x=%d y=%d\n", i, j, x[i][j], y[i][j]);writesi=0 j=0 x=1 y=2i=0 j=1 x=0 y=0i=1 j=0 x=2 y=2i=1 j=1 x=0 y=0. So then it becomes fairly obvious.