gpt4 book ai didi

python - 将 ByteArray 从 Python 传递给 C 函数

转载 作者:太空宇宙 更新时间:2023-11-04 03:21:46 25 4
gpt4 key购买 nike

我想将一个 ByteArray 变量从我的 Python 程序传递到我用 C 编写的 DLL,以加速某些在 Python 中速度太慢的特定处理。我浏览了 Web,尝试了 Ctypes 与 byref、cast、memoryviews、addressof 的组合,但没有任何效果。有没有什么简单的方法可以实现这一点,而无需将我的 ByteArray 复制到其他可以通过的东西中?这是我正在尝试做的事情:

/* 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 函数的好处?

奥利维尔

最佳答案

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

我没有你的 DLL,所以为了测试数组是否正确运行,我将使用 libc.strfry函数来洗牌它的字符。

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)

典型输出

bytearray(b'ABCDEF\x00')
bytearray(b'BFDACE\x00')

关于python - 将 ByteArray 从 Python 传递给 C 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45118153/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com