简体   繁体   English

C char数组到Python列表

[英]C char array to Python List

I have a C function as follows, 我有一个C函数,如下所示

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

I need to pass a pointer as msg_p into C code and be able to print the data in Python. 我需要将msg_p指针传递给C代码,并能够在Python中打印数据。 If I was doing this in C/C++, I would do this as follows, 如果我使用C / C ++进行此操作,则可以按以下方式进行操作,

char buf[ 64 ];
buf[0] = 0x22;//This is needed to prepare for something else.
buf[1] = 0x0f;
buf[2] = 0x61;
pldv_read( handle, buf, sizeof( buf ) );
//iterate buf and print the data

How do I do this in Python? 如何在Python中执行此操作? This is what I have so far in Python, but this seems to be crashing if my C code try to write into the buf. 这就是我到目前为止在Python中拥有的东西,但是如果我的C代码尝试写入buf,这似乎崩溃了。 I am working on Win7. 我正在使用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?

Use create_string_buffer : 使用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)

The reason it's crashing is that id returns the memory address of the internal PyObject that holds the string . 崩溃的原因是id返回包含字符串的内部PyObject的内存地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM