我在使用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的对象引用,但是如果我试图访问元素,就会出现分段错误。在
我做错什么了?在
感谢任何帮助。在
您的
service
类与gatt_primary
结构不匹配。uuid
应该是char
的数组,而不是指针:此外,对结构的返回字段使用强制转换不是一个好主意。看一下Structures and unions文档,您会发现对于fundamental data types,返回了相关联的python类型。所有其他派生类型都按原样返回。在
例如,
ctypes.cast(hndrange.contents.starthnd, ctypes.c_uint16)
将尝试将pythonint
类型强制转换为ctypes.c_uint16
。在相关问题 更多 >
编程相关推荐