【问题标题】:Pass a pointer to an array value from Cython to C将指向数组值的指针从 Cython 传递给 C
【发布时间】: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


【解决方案1】:

我愿意接受其他答案,但现在我想我会发布我的解决方案,希望它可以帮助其他人。

我使用 cytpes 而不是 Cython 解决了它。 我真的很想看到 Cython 解决方案

from ctypes import CDLL, Structure, POINTER, c_uint8, c_uint32, byref

class Msg(Structure):
    _fields_ = [("id", c_uint32), ("buf", POINTER(c_uint8))]

lib = CDLL('this_example.so')
get_msg = lib.recv_msg
get_msg.argtypes = [POINTER(Msg)]
get_msg.restype = None

data = (c_uint8 * 8)()
sample_msg = Msg(1, data)
get_msg(byref(sample_msg))
print sample_msg.id, sample_msg.buf[0]  # Should see changed data

【讨论】:

  • 您的解决方案很接近。我做了一些编辑。 buf 的类型是 POINTER(c_uint8)。你所拥有的相当于 C 中的(uint8_t*)[10]
猜你喜欢
  • 2017-08-09
  • 1970-01-01
  • 1970-01-01
  • 2020-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多