Problem marshalling memory allocated in C++ DLL
- From: "Martin Hignett" <ocularsinister@xxxxxxxxx>
- Date: 4 Jan 2007 09:56:45 -0800
I'm trying to marshal memory allocated in C++ DLL to a C# component.
The code I'm using is as follows:
void Initialise( HGLOBAL* phBuffer, DWORD* pdwLength )
{
CSharedFile mout( GHND );
CArchive arout( &mout, CArchive::store );
// Write some stuff to the archive...
arout.Close( );
*pdwLength = mout.GetLength( );
*phBuffer = mout.Detach( );
}
C# code is...
ref byte[] data
Int32 dataLength = 0;
IntPtr rawData = IntPtr.Zero;
if( NativeMethods.Initialise( ref rawData, ref dataLength ) != 0 )
{
return;
}
data = new Byte[dataLength];
Marshal.Copy( rawData, data, 0, dataLength );
Marshal.FreeHGlobal( rawData );
The code compiles and runs, but I've noticed the following:
* If I allocate the memory with the GPTR flag instead of GHND, the code
will run ~50% of the time correctly. The rest of the time it fails in
the C++ code with a memory exception, probably because GPTR is
non-movable memory and it was not possible to re-allocate without
moving the memory. However, the 50% of the time when this doesn't
happen, the C# marshalling code works and my data is correct.
* If I allocate the memory with a GHND flag, the C++ code never
crashes, but the marshalling always fails in the C#. That is, there are
no exceptions or errors (even on the FreeHGlobal), but the data
variable has junk in it.
I think I'm missing a trick here... perhaps rawData should not be
IntPtr type? Any help would be greatly appreciated!
--
Martin Hignett
.
- Follow-Ups:
- Re: Problem marshalling memory allocated in C++ DLL
- From: Mattias Sjögren
- Re: Problem marshalling memory allocated in C++ DLL
- Prev by Date: Re: ClassFactory cannot supply requested class
- Next by Date: Re: Visual component written in unmanaged C++
- Previous by thread: Re: ClassFactory cannot supply requested class
- Next by thread: Re: Problem marshalling memory allocated in C++ DLL
- Index(es):
Relevant Pages
|