2

我需要将 c++ dll 包装到 python。我正在ctypes为此使用模块。

c ++标头类似于:

class NativeObj
{
    void func();
}

extern "C"
{
    NativeObj* createNativeObj(); 

}; //extern "C"

我想NativeObj在 python 代码中创建,然后调用它的func方法。

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

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

谢谢。

4

1 回答 1

6

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

void callFunc(NativeObj* obj)
{
    obj->func();
}

然后你可以这样称呼它:

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

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)
于 2013-10-28T13:38:12.333 回答