访问递归Python ctypes structu时出现分段错误

2024-06-25 23:33:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我在使用Python ctypes访问嵌入到其他结构中的结构中的元素时遇到了困难。在

这是C:

struct GSList
{
    void* data;
    GSList* next;
};

struct att_range
{
    uint16_t start;
    uint16_t end;
};

struct gatt_primary
{
    char uuid[38];
    int changed;
    struct att_range* range;
};

typedef void( *python_callback_t )( GSList* services );

static python_callback_t pycb = NULL;

// pycb is set to a valid function pointer before the callback below is called.

static void primary_all_cb( GSList *services, uint8_t status )
{
    if( status == 0 ) {
        pycb( services );
    }
}

这是Python:

^{pr2}$

我使用的是python3.4和gcc4.7。这不包括最初调用以触发回调函数的函数或访问共享库的Python代码。我已经验证了所有的信息都填充了C语言中的结构,并且曾经能够在Python中打印uuid的内容。当我试图访问hndrange时,出现了一个分段错误。我可以用Python打印出hndrange的对象引用,但是如果我试图访问元素,就会出现分段错误。在

我做错什么了?在

感谢任何帮助。在


Tags: 元素uuidisservicecallbackstaticrange结构
1条回答
网友
1楼 · 发布于 2024-06-25 23:33:36

您的service类与gatt_primary结构不匹配。uuid应该是char的数组,而不是指针:

class service(ctypes.Structure):
    _fields_ = [
        ('uuid', ctypes.c_char*38),
        ('changed', ctypes.c_int),
        ('range', ctypes.POINTER(range))
    ]

此外,对结构的返回字段使用强制转换不是一个好主意。看一下Structures and unions文档,您会发现对于fundamental data types,返回了相关联的python类型。所有其他派生类型都按原样返回。在

例如,ctypes.cast(hndrange.contents.starthnd, ctypes.c_uint16)将尝试将python int类型强制转换为ctypes.c_uint16。在

相关问题 更多 >