I am trying to interoperate between Python and C++.
This is my C++ code for a test DLL method:
extern "C" __declspec(dllexport) PEParserNamespace::PEParserBase& _cdecl test(PEParserNamespace::PEParserBase* base) {
printf("the C++ function was called\n");
base->bytes = 12345;
return *base;
}
I try to use it from Python like so:
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))
I expected that testWrapper
to return the original PEParserBase
instance, but it doesn't - the reported id
values are different. The C++ code doesn't create any new instances of PEParserBase
or anything else, so I'm confident the problem has to be in the Python code.
Why does this happen, and how do I fix it?