访问ctypes返回对象的方法

Eli*_*sha 2 python ctypes

我需要将c ++ dll包装到python中.我正在使用ctypes模块.

c ++标题类似于:

class NativeObj
{
    void func();
}

extern "C"
{
    NativeObj* createNativeObj(); 

}; //extern "C"
Run Code Online (Sandbox Code Playgroud)

我想NativeObj用python代码创建然后调用它的func方法.

我写了这段代码并获得指针,NativeObj但我没有找到如何访问func

>>> import ctypes
>>> d = ctypes.cdll.LoadLibrary('dll/path')
>>> obj = d.createNativeObj()
>>> obj
36408838
>>> type(obj)
<type 'int'>
Run Code Online (Sandbox Code Playgroud)

谢谢.

Dav*_*nan 5

您不能从ctypes调用C++实例方法.您将需要导出将调用该方法的非成员函数.它在C++中看起来像这样:

void callFunc(NativeObj* obj)
{
    obj->func();
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样调用它:

import ctypes
d = ctypes.cdll.LoadLibrary('dll/path')
obj = d.createNativeObj()
d.callFunc(obj)
Run Code Online (Sandbox Code Playgroud)

告诉所ctypes涉及的类型也很有用.

import ctypes
d = ctypes.cdll.LoadLibrary('dll/path')

createNativeObj = d.createNativeObj
createNativeObj.restype = ctypes.c_void_p
callFunc = d.callFunc
callFunc.argtypes = [ctypes.c_void_p]

obj = createNativeObj()
callFunc(obj)
Run Code Online (Sandbox Code Playgroud)