小能豆

Python ctypes argtypes 用于类对象指针

py

我有此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我在这里需要使用什么正确的?


阅读 73

收藏
2025-03-02

共1个答案

小能豆

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))
2025-03-02