我已成功返回的指针从C++ DLL结构(包含wchar_t*
)成Python这样的: C++代码:上指针的矢量返回指针从C++ DLL到Python
...
typedef struct myStruct{
wchar_t* id;
wchar_t* content;
wchar_t* message;
} myStruct;
DLLAPI myStruct* DLLApiGetStruct(){
myStruct* testStruct = new myStruct();
testStruct->id = _T("some id");
testStruct->content = _T("some content");
testStruct->message = _T("some message");
return testStruct;
}
Python代码:
class MyPyStruct(Structure):
_fields_ = [
("id", c_wchar_p),
("content", c_wchar_p),
("message", c_wchar_p)
]
...
...
myDLL = cdll.LoadLibrary('myDLL.dll')
myDLL.DLLApiGetStruct.restype = POINTER(MyPyStruct)
result = myDLL.DLLApiGetStruct().contents
print result.id, result.content, result. message# those are valid values
好的,这工作正常,问题是,现在我需要返回指针的向量指向这些结构的指针。我已经试过这样:
C++代码:
typedef std::vector<myStruct*> myVector;
...
DLLAPI myVector* DLLApiGetVector(){
myVector* testVektor = new myVector();
for(i=0; i< 5; i++){
myStruct* testStruct = new myStruct();
testStruct->id = _T("some id");
testStruct->content = _T("some content");
testStruct->message = _T("some message");
testVektor->push_back(testStruct);
}
return testVektor;// all values in it are valid
}
Python代码:
#我认为,第一,第二行是不正确的(是正确的方法,使restype?):
vectorOfPointersType = (POINTER(DeltaDataStruct) * 5) #5 is number of structures in vector
myDLL.DLLApiGetVector.restype = POINTER(vectorOfPointersType)
vectorOfPointersOnMyStruct= myDLL.DLLApiGetVector.contents
for pointerOnMyStruct in vectorOfPointersOnMyStruct:
result = pointerOnMyStruct.contents
print result.id, result.content, result.message
值最后一排是无效的 - 这是一些内存随机配件我猜。 这是错误,我得到:
UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-11: character maps to <undefined>
非常感谢你的代码示例,它完美的工作。你能向我解释为什么'p [i] [0]'中有'[0]'? – Aleksandar
'p [i]'是一个指针。您可以选择使用'p [i] .contents'或获得第0个元素。就像我说的,我宁愿使用一系列结构。在这种情况下'p [i]'是一个'myStruct'实例。但我必须重写代码才能这样做。我想我会更接近你已有的东西。 – eryksun
你能否告诉我如何以及在什么时候释放记忆。我必须这样做,因为'result = new myStruct * [n];',对吧? – Aleksandar