我正在try 在Python和C++之间进行互操作.
以下是我的测试DLL方法的C++代码:
extern "C" __declspec(dllexport) PEParserNamespace::PEParserBase& _cdecl test(PEParserNamespace::PEParserBase* base) {
printf("the C++ function was called\n");
base->bytes = 12345;
return *base;
}
我try 在Python中使用它,如下所示:
import ctypes
#DataStructures.py
class PEParserBase(ctypes.Structure):
_fields_ = [("hFile", ctypes.c_void_p),
("dwFileSize", ctypes.c_ulong),
("bytes", ctypes.c_ulong),
("fileBuffer",ctypes.c_void_p)]
class PEHEADER(ctypes.Structure):
xc = 0
#FunctionWrapper.py
def testWrapper(peParserBase, _instanceDLL):
_instanceDLL.test.argtypes = [ctypes.POINTER(PEParserBase)]
_instanceDLL.test.restype = PEParserBase
return _instanceDLL.test(ctypes.byref(pEParserBase))
pEParserBase = PEParserBase()
print("hallo welt")
_test = ctypes.CDLL('PeParserPythonWrapper.dll')
print(id(testWrapper(pEParserBase, _test)))
print(id(pEParserBase))
我原以为testWrapper
会返回原始的PEParserBase
实例,但事实并非如此--报告的id
个值是不同的.C++代码不会创建PEParserBase
的任何新实例或其他任何内容,所以我确信问题一定出在Python代码中.
为什么会发生这种情况,我如何修复它?