C char数组到Python Lis

2024-10-02 08:17:50 发布

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

我有一个C函数,如下所示

int ldv_read( int handle, void* msg_p, unsigned length )

我需要将一个指针作为msg_p传递到C代码中,并且能够用Python打印数据。如果我在C/C++中这样做,我会这样做,

^{pr2}$

如何在Python中执行此操作?这是到目前为止我在Python中得到的结果,但是如果我的C代码试图写入buf,这似乎会崩溃。我正在研究Win7。在

from ctypes import*
ldv_open = windll.wldv32.ldv_open
ldv_open.restype = c_int
ldv_open.argtypes = [c_char_p]
deviceName = ('LDV/\\\\.\Lonusb8-4')
handle = ldv_open(deviceName)

buf = c_char * 1024 #  <----clearly, this isn't a list, don't know how to create a char list in Python.
ldv_read = windll.wldv32.ldv_read
ldv_read.restype = c_int
ldv_read.argtypes = [c_int,c_void_p,c_uint]
res = ldv_read( handle, id(buf), len(buf) )
#how do I print my buf here?

Tags: 代码readmsgopeninthandlecharbuf
1条回答
网友
1楼 · 发布于 2024-10-02 08:17:50

使用create_string_buffer

buf = create_string_buffer("\x22\x0F\x61", 64)
ldv_read = windll.wldv32.ldv_read
ldv_read.restype = c_int
ldv_read.argtypes = [c_int,c_void_p,c_uint]
res = ldv_read( handle, buf, len(buf) )
print(buf.raw)

它崩溃的原因是id返回保存字符串的内部PyObject的内存地址。在

相关问题 更多 >

    热门问题