Reputation: 418
I have a C function as follows,
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. If I was doing this in C/C++, I would do this as follows,
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? 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. I am working on 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?
Upvotes: 0
Views: 1779
Reputation: 10727
Use 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.
Upvotes: 1