gpt4 book ai didi

Python-Ctypes : How to pass Void* as argument

转载 作者:行者123 更新时间:2023-12-01 05:44:12 28 4
gpt4 key购买 nike

我必须在 CTypes 中使用 DLL 中的 2 个函数。这些函数有一个 void* 作为参数。但无论我如何尝试,我都无法使其发挥作用。我收到一条错误消息,告诉我我使用了错误的类型。我看过很多帖子并阅读了文档,但我无法弄清楚。任何帮助,将不胜感激。我在 Windows 上使用 Python 2.7。

我的 C 函数是:

void WriteRam(unsigned address, unsigned length, void* buffer)
void ReadRam(unsigned address, unsigned length, void* buffer)

在 Python 中,我尝试将列表传递给函数,如下所示:

audioVolume = 32767
for i in range(buffSize):
txBuff.append(int(audioVolume * math.sin(i)) )
WriteRam(0, 64, txBuff)

我的Python函数是:

WriteRam = DPxDll['DPxWriteRam']
def DPxWriteRam(address=None, length=None, buffer=None):
#test = ctypes.c_void_p.from_buffer(buffer) # not working
#p_buffer = ctypes.cast(buffer, ctypes.c_void_p) # not working
p_buffer = ctypes.cast(ctypes.py_object(buffer), ctypes.c_void_p) # not working
#p_buffer = ctypes.c_void_p() # not working
WriteRam.argtypes = [ctypes.c_uint, ctypes.c_uint, ctypes.c_void_p]
WriteRam(address, length, ctypes.byref(p_buffer))

最佳答案

假设 txBuff 是一个整数列表,那么您需要将它们打包到一个数组中。下面的代码应该可以工作,但我无法测试它......

def DPxWriteRam(address, int_list):
int_size = ctypes.sizeof(ctypes.c_int)
item_count = len(int_list)
total_size = int_size * item_count
packed_data = (ctypes.c_int * item_count)(*int_list)
WriteRam(ctypes.c_uint(address), ctypes.c_uint(total_size), packed_data)

DPxWriteRam(whatever, [0, 1, 2, 3])

...尽管如果 WriteRam 几乎只是执行 memcpy(),那么您可以使用这个...

import ctypes
libc = ctypes.CDLL('msvcrt.dll')

def DPxWriteRam(address, int_list):
int_size = ctypes.sizeof(ctypes.c_int)
item_count = len(int_list)
total_size = int_size * item_count
packed_data = (ctypes.c_int * item_count)(*int_list)
libc.memcpy(address, packed_data, total_size)

...我可以测试...

>>> l = range(4)
>>> p = libc.malloc(1000)
>>> DPxWriteRam(p, l)
>>> s = ' ' * 16
>>> libc.memcpy(s, p, 16)
>>> print repr(s)
'\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00'

关于Python-Ctypes : How to pass Void* as argument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16676739/

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