Python 2d Array I C Using Ctypes
i'm trying to use a self written c lib to proces 2d array from python but with little success. Here is my c code: CamLibC.c int TableCam(const int x, const int y, int **Array) {
Solution 1:
c_long
is the same asc_int
, but that is not the problem.
There are a number of issues:
- The type of
numpy.zeros
is default float. - In the Python
TableCam
,A
is never modified. - In the C
TableCam
, the 3rd parameter should beint* Array
and the elements modified by computingi*y+j
. That also agrees withargtypes
, which was correct. - The numpy array can be coerced to the right
ctypes
type.
Corrected code (on Windows, for my testing):
cam.c
#include<stdio.h>
__declspec(dllexport) voidTableCam(constint x, constint y, int *Array){
int i,j;
for (i = 0; i < x; i++)
for (j = 0; j < y; j++)
Array[i*y+j] = 1;
}
camlib.py
importctypes_CamLib= ctypes.CDLL('cam')
_CamLib.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_int)]
_CamLib.restype = None
def TableCam(A):
x,y = A.shapearray= A.ctypes.data_as(ctypes.POINTER(ctypes.c_int))
_CamLib.TableCam(x,y,array)
test.py
import camlib
import numpy as np
Anum = np.zeros((3,3),dtype=np.int)
print('Start:')
print(Anum)
camlib.TableCam(Anum)
print('Ended:')
print(Anum)
Output
Start:
[[0 0 0]
[0 0 0]
[0 0 0]]
Ended:
[[1 1 1]
[1 1 1]
[1 1 1]]
Post a Comment for "Python 2d Array I C Using Ctypes"