我有此C++
代码,可以将Foo
基于类的代码集成到 python 中。
class Foo{
public:
Foo(){};
int do_thing(int arg){ return arg*2; }
};
extern "C" {
Foo* get_foo_obj(){
return new Foo;
}
int do_thing(Foo* ptr, int arg){
return ptr->do_thing(arg);
}
}
现在我想为 python 中的函数分配argtypes
和。restype
lib = ctypes.CDLL("mylib.so")
lib.get_foo_obj.restype = <POINTER?>
lib.do_thing.argtypes = (<POINTER?>, c_int)
lib.do_thing.restype = c_int
ctypes
我在这里需要使用什么正确的?
ctypes.c_void_p
有效(void*
在 C 语言中),尽管使用不透明指针类型可以实现更多的类型安全,例如:
import ctypes as ct
class Foo(ct.Structure):
pass
lib = ct.CDLL('mylib.so')
lib.get_foo_obj.argtypes = ()
lib.get_foo_obj.restype = ct.POINTER(Foo)
lib.do_thing.argtypes = ct.POINTER(Foo), ct.c_int
lib.do_thing.restype = ct.c_int
foo = lib.get_foo_obj()
print(lib.do_thing(foo, 5))