How to convert an IntPtr back into an object

Nick picture Nick · Apr 8, 2009 · Viewed 18k times · Source

All, this is a follow up from a previous question here: C# formatting external Dll function parameters

Here specifically is the code that I am trying to convert to C#:

FILES_GetMemoryMapping((LPSTR)(LPCTSTR)MapFile, &Size, (LPSTR)MapName, &PacketSize, pMapping, &PagePerSector);
// Allocate the mapping structure memory
pMapping = (PMAPPING)malloc(sizeof(MAPPING));
pMapping->NbSectors = 0;
pMapping->pSectors = (PMAPPINGSECTOR) malloc((Size) * sizeof(MAPPINGSECTOR));

// Get the mapping info
FILES_GetMemoryMapping((LPSTR)(LPCTSTR)MapFile, &Size, (LPSTR)(LPCTSTR)MapName, &PacketSize, pMapping, &PagePerSector);

The function "FILES_GetMemoryMapping" gets called twice, I'm guessing the first time to get the size of the struct, and the second to actually fill it.

the "pMapping" is a pointer to a struct in C++, In my C# code, I have pMapping as type IntPtr. The next line I can converted to :

pMapping = Marshal.AllocHGlobal(Marshal.SizeOf(new UM0516.Mapping()));

With (UM0516.Mapping) being the struct. Cool, so I've just allocated some space that IntPtr is pointing to. Now for the next line... "pMapping->NbSectors = 0;"

How am I suppose to go into the now allocated unmanaged memory space, type cast it as a (UM0516.Mapping) struct, and set one of its members? Then make sure i didn't screw with it too much so that the second time I call "FILES_GetMemoryMapping", it can now use this struct??

-- Ok, I've taken some advice and now have this:

I tried this and I get a "AccessViolationException was unhandled" exception on the first "FILES_GetMemoryMapping" call

Here is what I have:

string filepath = @"C:\blah.blah";
string MapFile = @"D:\blah.blah";
UM0516.Mapping myMapping = new UM0516.Mapping();
IntPtr pMapping = Marshal.AllocHGlobal(Marshal.SizeOf(myMapping));
Marshal.StructureToPtr(myMapping, pMapping, false);
ushort PacketSize = 0;
ushort size = 0;
string MapName = String.Empty;
byte PagePerSector = 0;

uint b7 = UM0516.FILES_GetMemoryMapping(MapFile, out size, MapName, out PacketSize, pMapping, out PagePerSector);

Do you think this exception is coming from the "pMapping" parameter? Could this come from anything else that I've passed in?

Answer

Adam Robinson picture Adam Robinson · Apr 8, 2009

In order to get the IntPtr, what you'll want to do is create your structure, set any options that you may need to, allocate the memory like you already have, then call..

System.Runtime.InteropServices.Marshal.StructureToPtr(yourStructVariable, pMapping, false);

This will copy the data from your populated structure into your allocated memory.

To copy data from the memory into a new structure named 'mapping', call...

UM0516.Mapping mapping = (UM0516.Mapping)System.Runtime.InteropServices.Marshal.PtrToStructure(pMapping, typeof(UM0516.Mapping))