简体   繁体   中英

passing python array to c++ function using ctypes

I'm still new to this kind of extending (though I've a good background in C++ and python)

what I wanted is to use ctypes module to pass data to a C++ function example that worked so far for me:

test.dll file

#define DLLEXPORT extern "C" __declspec(dllexport)

DLLEXPORT int sum(int a, int b) {
    return a + b;
}

sum_test.py file:

from ctypes import cdll
mydll = cdll.LoadLibrary('test.dll')
mydll.sum(5, 3)

result is 8 which works well...

note: I'm using this to develop an Addon(plugin) for blender, the data which I will pass to the C++ function is a huge array (Tuple or whatever type of array), this data will be passed to GPU to process it with OpenCL

mainly the workflow in C++ is passing a pointer (which will copy the whole array data to the GPU)

so the question is: the best way (fastest too) to get that tuple pointer inside C++ (hopefully with explaining what happens in python and in C++)

The easiest way is to tell ctypes that the function takes a pointer to an array of a certain type, in many cases Python/ctypes will figure out the rest.

libc = CDLL('libc.so.6') # on Debian/Linux
printf = libc.printf
printf.restype = c_int
printf.argtypes = [POINTER(c_char), c_int]
printf('< %08x >', 1234)

This assumes that the function will simply take a pointer. If your function takes for example exactly five floats, you could provide c_float * 5 as according parameter type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM