简体   繁体   English

如何在ctypes中返回指向结构的指针?

[英]How to return a pointer to a structure in ctypes?

I try to pass a pointer of a structure which is given me as a return value from the function 'bar' to the function 'foo_write'. 我尝试传递一个结构的指针,该结构从函数'bar'返回给函数'foo_write'作为返回值。 But I get the error message 'TypeError: must be a ctypes type' for line 'foo = POINTER(temp_foo)'. 但是我得到'foo = POINTER(temp_foo)'行的错误消息'TypeError:必须是ctypes类型'。 In the ctypes online help I found that 'ctypes.POINTER' only works with ctypes types. ctypes在线帮助中,我发现'ctypes.POINTER'仅适用于ctypes类型。 Do you know of another way? 你知道另一种方式吗? What would you recommend? 你会推荐什么?

C: C:

typedef struct FOO_{
    int i;
    float *b1;
    float (*w1)[];
}FOO;

foo *bar(int foo_parameter) {...
void foo_write(FOO *foo)

Python with ctypes: Python与ctypes:

class foo(Structure):
    _fields_=[("i",c_int),
              ("b1",POINTER(c_int)),
              ("w1",POINTER(c_float))]

temp_foo=foo(0,None,None)
foo = POINTER(temp_foo)
foo=myclib.bar(foo_parameter)
myclib.foo_write(foo)

Change 更改

foo = POINTER(temp_foo)

to

foo = pointer(temp_foo)

can solve the problem. 可以解决问题。

Please see http://docs.python.org/library/ctypes.html#ctypes-pointers for more information. 有关更多信息,请参阅http://docs.python.org/library/ctypes.html#ctypes-pointers

Your bar function has an incorrect definition, I guess you mean it is struct FOO_ *bar(int); 你的bar函数有一个不正确的定义,我猜你的意思是它是struct FOO_ *bar(int); ?

The Python code is wrong in the sense that foo_parameter is never declared, so I'm not 100% sure what you want to do. 从未声明foo_parameter的意义上的Python代码是错误的,所以我不能100%确定你想要做什么。 I assume you want to pass a parameter of your python-declared foo , which is an instance of a struct FOO_ , into the C bar(int) and get back a pointer to struct FOO_ . 我假设您要将python声明的foo的参数(它是struct FOO_一个实例) struct FOO_到C bar(int)并返回指向struct FOO_的指针。

You don't need POINTER to do that, the following will work: 您不需要POINTER来执行此操作,以下操作:

#!/usr/bin/env python
from ctypes import *

class foo(Structure):
    _fields_=[("i",c_int),
              ("b1",POINTER(c_int)),
              ("w1",POINTER(c_float))]

myclib = cdll.LoadLibrary("./libexample.so")
temp_foo = foo(1,None,None)
foovar = myclib.bar(temp_foo.i)
myclib.foo_write(foovar)

Since CTypes will wrap the return type of bar() in a pointer-to-struct for you. 因为CTypes会将指向结构的返回类型bar()包装回来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM