将ByteArray从Python传递到C函数

2024-10-01 11:36:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将ByteArray变量从Python程序传递到用C编写的DLL中,以加速某些在Python中太慢的特定处理。我浏览过网络,试过用byref,cast,memoryviews,addressof组合的Ctypes,但是没有任何效果。有没有什么简单的方法可以做到这一点,而不必把我的旁白复制到其他可以通过的东西中? 以下是我要做的:

/* 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)

但是在将第一个参数(MyData)传递给C函数时,我得到了一个类型错误。在

有没有不需要太多开销的解决方案会浪费C函数的优点?在

奥利维尔


Tags: 函数程序网络myresultintbooldll
1条回答
网友
1楼 · 发布于 2024-10-01 11:36:50

我假设ByteArray应该是bytearray。我们可以使用^{}创建一个可变字符缓冲区,它是ctypesctypes数组。但是create_string_buffer不会接受bytearray,我们需要给它传递一个bytes对象来初始化它;幸运的是,bytes和{}之间的转换是快速有效的。在

我没有你的DLL,所以为了测试数组的行为是否正确,我将使用^{}函数来洗牌它的字符。在

from ctypes import CDLL, create_string_buffer

libc = CDLL("libc.so.6") 

# Some test data, NUL-terminated so we can safely pass it to a str function.
mydata = bytearray([65, 66, 67, 68, 69, 70, 0])
print(mydata)

# Convert the Python bytearray to a C array of char
p = create_string_buffer(bytes(mydata), len(mydata))

#Shuffle the bytes before the NUL terminator byte, in-place.
libc.strfry(p)

# Convert the modified C array back to a Python bytearray
newdata = bytearray(p.raw)
print(newdata)

典型输出

^{pr2}$

相关问题 更多 >