0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It fixed the crash, thank you. However, print(buf.raw) prints garbage. By looking at logs from my C code, I know I should be seeing few lines that looks like "0000 18 4A 20 02 3C 00 01 81 00 00 11 00 01 01 00 00 00 01 01 00 01 01 00 00 32 32 00 D0 00 E0 00 F0". Is this something to do with Unicode? If so, how do I fix this?
@usustarr Python prints strings differently than C does. To see it like you want, use for c in buf.raw: print hex(ord(c))[2:].zfill(2),.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.