I have written the following code to modify my custom python class Point
using the ctypes
library, following the approch I found in this tutorial. The wrap_function
is just a little helper for ease of use, as this is a MWE from a bigger project.
On the python side:
import ctypes
import numpy as np
libc = ctypes.WinDLL(r'C:\Path\lib.dll')
def wrap_function(lib, funcname, restype, argtypes):
func = lib.__getattr__(funcname)
func.restype = restype
func.argtypes = argtypes
return func
class Point(ctypes.Structure):
_fields_ = [('x', ctypes.c_int), ('xdata', ctypes.c_void_p)]
list_of_points = [] #unused for now
xdata = np.zeros((40000,), dtype=np.double)
a = Point(1,xdata.ctypes.data)
b = Point(3,xdata.ctypes.data)
change_data_for_point = wrap_function(libc,'change_data_for_point', None, [ctypes.POINTER(Point)])
change_data_for_point(a)
And on the C-side:
---header:
const int N = 40000;
typedef struct {
double x;
double xdata[N];
} Point;
extern "C" LIB_API void change_data_for_point(Point* p);
---source:
void change_data_for_point(Point* p) {
p->x++;
for (int i = 0; i < 40000; i++) {
p->xdata[i] = 2.0*i;
if (i % 1000 == 0) printf("xdata at index %d is %f\n", i, p->xdata[i]);
}
}
When executing the python file in Windows 7 cmd
, it prints the following output:
xdata at index 0 is 0.000000
xdata at index 1000 is 2000.000000
// ... some more ...
xdata at index 17000 is 34000.000000
xdata at index 18000 is 36000.000000
Traceback (most recent call last):
File "test.py", line 40, in <module>
Why does it stop at 18.000 ? I tried it several times, sometimes the loop reaches 19 or 20k, but it never gets higher than that. Does it have something to do with the array initialization on the C-side? Did I mess up the parameter passing on the python side?
Bonus question: How can I pass a list of these points to the C-side with ctypes?