我想将Python程序中的ByteArray变量传递给我用C编写的DLL,以便加速某些特定的处理,这些处理在Python中速度太慢。我已经通过网络,尝试了与C#参数组合,byref,cast,memoryviews,addressof,但没有任何作用。有没有简单的方法来实现这一点,而不是将我的ByteArray复制到其他将会通过的东西? 这里就是我想要做:将ByteArray从Python传递到C函数
/* My C DLL */
__declspec(dllexport) bool FastProc(char *P, int L)
{
/* Do some complex processing on the char buffer */
;
return true;
}
# My Python program
from ctypes import *
def main(argv):
MyData = ByteArray([1,2,3,4,5,6])
dll = CDLL('CHELPER.dll')
dll.FastProc.argtypes = (c_char_p, c_int)
dll.FastProc.restype = c_bool
Result = dll.FastProc(MyData, len(MyData))
print(Result)
但传递的第一个参数(迈德特)C函数时,我得到一个类型错误。
是否有任何解决方案不需要太多的开销会浪费我的C函数的好处?
奥利维尔
什么是'ByteArray'?它不应该是'bytearray'(全部小写)吗?你在使用Python 3吗? –
是它的一个字节数组,对于输入错误 – Marmotte06
创建一个长度相同的ctypes数组类型,并将'bytearray'传递给它的['from_buffer'](https://docs.python.org/3/library/ctypes。 html#ctypes._CData.from_buffer)contsructor,例如'L = len(MyData);''P =(ctypes.c_char * L).from_buffer(MyData);''dll.FastProc(P,L)'。 – eryksun