Another problem with Marshalling

  • Thread starter =?ISO-8859-1?Q?Marc-Aur=E8le_Brothier?=
  • Start date
?

=?ISO-8859-1?Q?Marc-Aur=E8le_Brothier?=

Hi,

Well I went further but now I'm stuck with the latest "hard" point in my
program. I have this structure in C++

typedef struct _PACKET {
PVOID Buffer;
UINT Length;
UINT ulBytesReceived;
BOOL bIoComplete;
} PACKET, *LPPACKET;

"PVOID Buffer" will received an array of byte of size 256*1024. I need
to allocate this array in my C# program. The C++ Dll will insert the
data in the structure and I need to read this new value in my C# program.

The corresponding structure in C#:
[StructLayoutAttribute(LayoutKind.Sequential)]
public struct PACKET
{
public IntPtr Buffer;
public uint Length;
public uint ulBytesReceived;
public bool bIoComplete;
}

Declaration of the function
C++:
BOOLEAN PacketReceivePacket(LPADAPTER AdapterObject,LPPACKET
lpPacket,BOOLEAN Sync);

C#:
[ DllImport( "Packet32.dll", SetLastError=true,
EntryPoint="PacketReceivePacket" ) ]
private static extern bool DllPacketReceivePacket(IntPtr pHandle, IntPtr
pPacket, bool sync);


And here is the function where I use all the previous stuff:

public bool ReceivePacket(out byte[] data, out uint bytesReceived, bool
sync)
{
IntPtr tmp, tmp2;
PACKET packet;
tmp = LocalAlloc(MemoryAllocFlags.LPTR,
(uint)Marshal.SizeOf(typeof(Packet32.ADAPTER)));
tmp2 = LocalAlloc(MemoryAllocFlags.LPTR,
(uint)Marshal.SizeOf(typeof(Packet32.PACKET)));
packet.ulBytesReceived = 0;
packet.bIoComplete = false;
packet.Length = 256*1024;
byte[] test = new byte[256*1024];
packet.Buffer = LocalAlloc(MemoryAllocFlags.LPTR, (uint)test.Length);
if (packet.Buffer == IntPtr.Zero)
throw new OutOfMemoryException("Couldn't allocate memory for message
buffer");
else
Marshal.Copy(test, 0, packet.Buffer, test.Length);
data = null;
try
{
Marshal.StructureToPtr(adapterHandle, tmp, false);
Marshal.StructureToPtr(packet, tmp2, false);
bool res = DllPacketReceivePacket(tmp, tmp2, sync);
Marshal.PtrToStructure(tmp2, packet);
bytesReceived = packet.ulBytesReceived;
LocalFree(tmp);
LocalFree(tmp2);
return res;
}
catch(Exception e)
{
string msg = e.Message;
LocalFree(tmp);
LocalFree(tmp2);
}
bytesReceived = 0;
return false;
}


I check in the C++ Dll, and the value of PACKET.ulBytesReceived is
correctly modified, but I don't get back the new value in the C# program
after the marshalling of the pointer to the structure... Can someone
tell me what is wrong?


Thank you in advance!

/Marco
 
?

=?ISO-8859-1?Q?Marc-Aur=E8le_Brothier?=

Found...

Shouldn't write this line to get back the data
Marshal.PtrToStructure(tmp2, packet);

but
packet = (Packet32.PACKET) Marshal.PtrToStructure(tmp2,
typeof(Packet32.PACKET));

/Marco
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top