0

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.

2
  • whats the return type? Commented Oct 24, 2013 at 21:36
  • the return type is a bool Commented Oct 25, 2013 at 4:43

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.