2013-10-24 43 views
0

我想寫一個託管的C++/CLI包裝到非託管類。一個類中的方法具有類似於指針指針C++/CLI包裝

audiodecoder::Decode(byte *pEncodedBuffer, unsigned int uiEncodedBufLen, byte **pDecodedAudio, unsigned int *uiDecodedAudioLen) 

簽名,其中*是pEncodedBuffer指針編碼的音頻樣本和** pDecodedAudio是其中函數將初始化存儲器並存儲解碼的音頻。事實上,數據是音頻應該是沒有任何意義的。

這個方法的包裝會如何看起來像?任何建議都會有所幫助。

+0

什麼是返回類型? – user1937198

+0

返回類型是bool – Saibal

回答

1

託管代碼的一個好處是它使用垃圾回收器並擁有強類型的數組。所以很好的支持返回數組作爲函數返回值。這使您理想的包裝功能是這樣的:

array<Byte>^ Wrapper::Decode(array<Byte>^ encodedBuffer) { 
     pin_ptr<Byte> encodedPtr = &encodedBuffer[0]; 
     Byte* decoded = nullptr; 
     unsigned int decodedLength 
     int err = unmanagedDecoder->Decode(encodedPtr, encodedBuffer->Length, &decoded, &decodeLength); 
     // Test err, throw an exception 
     //... 
     array<Byte>^ retval = gcnew array<Byte>(decodedLength); 
     Marshal::Copy((IntPtr)decoded, retval, 0, decodedLength); 
     free(decoded); // WATCH OUT!!! 
     return retval; 
    } 

請注意// WATCH OUT評論。您需要銷燬解碼器分配的緩衝區。正確做到這一點需要知道解碼器如何管理其內存,並且通常使得它非常重要,因爲您的C++/CLI代碼與解碼器模塊共享相同的CRT。如果沒有好的協議或者你無法編譯解碼器源代碼,這往往會出錯。

+0

謝謝漢斯。這真的有幫助。 – Saibal