ctypes中的c_void_p从python调用时返回“ int”

问题描述

我正在尝试通过ctypes使用C堆栈实现包装器。

我的数据结构是:

/**
 * Module with @R_422_4045@ion for stack data type
 * */

// Element structure
struct element {
    struct element *last;
    struct element *next;
    void *val;
};

typedef struct element element;

// Stack structure
struct stack {
    struct element *head;
    int nelem;
};

typedef struct stack stack;

element *new_element(void *);
void del_element(element *);

包装:

class c_element(ctp.Structure):
    """
    Structure class representing a stack element

    @var last: pointer to last element
    @var next: pointer to next element
    @var val: (void) pointer to stored element
    """
    pass

c_element._fields_=[
    ('last',ctp.POINTER(c_element)),('next',('val',ctp.c_void_p)
]

c_element_p=ctp.POINTER(c_element)

class c_stack(ctp.Structure):
    """
    Class representing a stack

    @var head: pointer to first element
    @var nelem: number of elements
    """
    _fields_=[
    ('head',c_element_p),('nelem',ctp.c_int)
]

c_stack_p=ctp.POINTER(c_stack)

我(在另一个C函数中)将node *变量(节点是另一个结构,我认为与该问题无关,不值得转录)分配给element.val

当我尝试打印时

ep=c_element() # or allocating a struct element * within function new_element(),see header above: 
# all it does is a call to malloc and a NULL pointer verification
print(type(ep.contents.val))

pst=new_stack() # calling a wrapped C function to create an empty stack
print(type(pst.contents.head.contents.val))

我两次都得到<class 'int'>。 在ctypes结构内分配空指针时,我缺少什么吗? 类型应该是ctypes.c_void_p,不是吗? 从C调用时,其他应访问结构中void指针指向的结构中的变量的C函数在从C调用时可以正常工作,但在使用ctypes包装器时会失败。

我正在使用的所有结构都在C函数中动态分配。

预先感谢

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)