简体   繁体   English

在Python Ctypes回调中接收非Null-Terminated数据

[英]Receiving non Null-Terminated data in Python Ctypes callback

I'm Writing a Python ctypes wrapper for a DLL. 我正在为DLL编写Python ctypes包装器。

When an event occurs, the DLL attempts to call a callback function with the following prototype: 当事件发生时,DLL尝试使用以下原型调用回调函数:

void Function(u8 *Data, u16 Length)

Essentially, it gives us a pointer to a buffer of raw data, and a length of that buffer. 从本质上讲,它为我们提供了一个指向原始数据缓冲区的指针,以及该缓冲区的长度。

I'm trying to find a method of receving and processing this data in my python code. 我正在尝试在python代码中找到一种接收和处理这些数据的方法。

If I declare the ctypes function type as a char pointer: 如果我将ctypes函数类型声明为char指针:

TX_CALLBACK_FUNC_TYPE = CFUNCTYPE(None, c_char_p, c_int)

then the data is treated as a null terminated string, and I get truncated data if any 0x00 bytes exist in the buffer. 然后将数据视为空终止字符串,如果缓冲区中存在任何0x00字节,则会得到截断数据。

If I declare the ctypes function type as a void pointer: 如果我将ctypes函数类型声明为void指针:

TX_CALLBACK_FUNC_TYPE = CFUNCTYPE(None, c_void_p, c_int)

then I get a long integer value, which I assume is the address of the raw data - but I don't know how to retrieve the data to use it in Python. 然后我得到一个长整数值,我假设是原始数据的地址 - 但我不知道如何检索数据以在Python中使用它。

If I declare the ctypes function type as a POINTER to char: 如果我将ctypes函数类型声明为char的POINTER:

TX_CALLBACK_FUNC_TYPE = CFUNCTYPE(None, POINTER(char), c_int)

then I get a ctypes.LP_c_char object, but I can't figure out how to access the raw data in the object. 然后我得到一个ctypes.LP_c_char对象,但我无法弄清楚如何访问对象中的原始数据。

What's the best way to access raw data in Python which is returned from a wrapped DLL? 从包装的DLL返回的Python中访问原始数据的最佳方法是什么?

You need a buffer: 你需要一个缓冲区:

>>> import ctypes
>>> b = ctypes.c_buffer("abc\0def", 16)
>>> b.value
'abc'
>>> b.raw
'abc\x00def\x00\x00\x00\x00\x00\x00\x00\x00\x00'

To get the data out of a ctypes.LP_c_char just slice it . 要从ctypes.LP_c_char获取数据,只需将其切片即可

def processBytes(pBuffer,len):<br>
   <b>print(pBuffer[:len])</b>


CB_FUNC_TYPE = ctypes.CFUNCTION(None, ctypes.POINTER(ctypes.c_char),ctypes.c_int)<br>
cb_func = CB_FUNC_TYPE(processBytes)


//Need to setup cb_func in C <br>
//In C assign your call-back function<br>
void (*c_cb_func)(char *, int) = cb_func<br>

// Call your python function from C<br>
(c_cb_func)(pBuffer,len)

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

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