【发布时间】:2018-09-13 00:13:44
【问题描述】:
我在 C 中有一个如下所示的结构:
typedef struct {
uint32_t id;
uint8_t *buf; // pointer to message data
} msg_t;
还有一些函数接收指向这种结构的指针并修改它。
void recv_msg( msg_t *msg ) {
// Stuff happens to message here
return;
}
对于 cytpes,我尝试过这样的事情:
from cytpes import CDLL, Structure, POINTER, c_ubyte, c_uint32
class Msg(Structure):
_fields_ = [("id", c_uint32), ("buf", POINTER(c_ubyte * 10))]
lib = CDLL("this_example.so")
get_msg = lib.recv_msg
get_msg.argtypes = [POINTER(Msg)]
get_msg.restype = None
sample_data_array = POINTER(c_ubyte * 10)()
data = sample_data_array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
sample_msg = Msg(1, data)
get_msg(sample_msg)
print sample_msg.id, sample_msg.buf[0] # Should change data
我得到一个 TypeError('expected LP_c_ubyte_Array_10 instance, got list',)
我也尝试过使用 Cython 的类似方法:
from libc.stdint cimport uint8_t, uint32_t
cdef extern from "this_example.h":
ctypedef struct msg_t:
uint32_t id;
uint8_t *buf;
void get_msg (msg_t *)
def recv_msg():
# How I would do this I don't know
print msg.id, msg.buf[0]
我还应该补充一点,我不想使用 numpy(但如果必须的话,我会很不情愿地使用)。此外,数据数组的长度可以变化,但我在 msg 结构中也有一个长度变量,因此我可以将其初始化为正确的发送长度,并将其设置为默认值和接收的最大长度。
有什么线索吗?谢谢!
【问题讨论】:
-
C 不支持传递引用。它是严格值传递。指针不是引用。
标签: python c pointers cython ctypes