I have this C
code to integrate my class Foo
based code into 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);
}
}
Now I want to assign argtypes
and restype
for the functions from python.
lib = ctypes.CDLL("mylib.so")
lib.get_foo_obj.restype = <POINTER?>
lib.do_thing.argtypes = (<POINTER?>, c_int)
lib.do_thing.restype = c_int
What would be the correct ctypes
I need to use here?
CodePudding user response:
ctypes.c_void_p
works (void*
in C), although you can be more type safe with an opaque pointer type like:
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))