Problem marshalling memory allocated in C++ DLL

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



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

.



Relevant Pages

  • Re: Is there a maximum contiguous memory allocation?
    ... but could ALLOCATE it! ... allocate it if I had 2GB of physical memory! ... the amount of physical memory I have installed. ... Note that you can use raw VirtualAlloc to improve your ...
    (microsoft.public.vc.mfc)
  • Re: The Lisp Curse
    ... Memory is allocated and free'd behinds the scenes in C ... But that calls malloc or libc, ... Most C file I/O functions allocate space from a storage device, ...
    (comp.lang.forth)
  • Re: experienced opinions
    ... think a multiple process model is ... Every time a threaded process allocates memory or allocate a file ... If multiple processes map shared memory or shared files, ...
    (comp.unix.programmer)
  • Re: XPC-target, s function problem
    ... You haven't said how you're allocating the memory for the matrices ... allocate all of the arrays from the heap using malloc. ... In trying to run an S function on xPC target built using the S function ... that with offline simulation everything works perfectly with bigger ...
    (comp.soft-sys.matlab)
  • Tru64 issues with Infinite limits
    ... An automated test in my nightly build was failing due to Out of Memory ... Cannot allocate block 146 ...
    (comp.unix.tru64)