Pointer to a pointer C++/CLI wrapper
I am trying to write a managed C++/CLI wrapper to unmanaged class. One of the methods in the class has a signature like
audiodecoder::Decode(byte *pEncodedBuffer, unsigned int uiEncodedBufLen, byte **pDecodedAudio, unsigned int *uiDecodedAudioLen)
where *pEncodedBuffer is pointer to encoded audio sample and **pDecodedAudio is where the function would initialize memory and store the decoded audio. Actually that the data is audio should be of no consequence.
How would the would the wrapper for this method look like? Any suggestion would be helpful.
A nicety of managed code is that it uses a garbage collector and has strongly typed arrays. So returning an array as a function return value is well supported. Which makes your ideal wrapper function something like this:
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;
}
Do note the // WATCH OUT
comment. You need to destroy the buffer that the decoder allocated. Doing this correctly requires knowing how the decoder manages its memory and usually makes it very important that your C++/CLI code shares the same CRT as the decoder module. This tends to go wrong badly if there is no good protocol or you can't compile the decoder source code.
上一篇: 使用托管参数管理非托管回调?
下一篇: 指向C ++ / CLI包装器的指针