我已成功返回的指針從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