简体   繁体   English

使用ctypes将python数组传递给c ++函数

[英]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) 我仍然是这种扩展的新手(尽管我在C ++和python方面有很好的背景)

what I wanted is to use ctypes module to pass data to a C++ function example that worked so far for me: 我想要的是使用ctypes模块将数据传递给目前为我工作的C ++函数示例:

test.dll file test.dll文件

#define DLLEXPORT extern "C" __declspec(dllexport)

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

sum_test.py file: sum_test.py文件:

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

result is 8 which works well... 结果是8,效果很好......

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 注意:我正在使用它来为blender开发一个Addon(插件),我将传递给C ++函数的数据是一个巨大的数组(元组或任何类型的数组),这些数据将被传递给GPU来处理它使用OpenCL

mainly the workflow in C++ is passing a pointer (which will copy the whole array data to the GPU) 主要是C ++中的工作流传递指针(将整个数组数据复制到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++) 所以问题是:在C ++中获取该元组指针的最佳方法(也是最快)(希望能解释python和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. 最简单的方法是告诉ctypes该函数采用指向某种类型数组的指针,在很多情况下Python / ctypes会找出其余部分。

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. 如果你的函数只有五个浮点数,你可以提供c_float * 5作为参数类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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