views:

777

answers:

3

I have yet to find a good reference on this topic. For this example we will take some C++ code that I'm trying to port over to C#.

In C++ land we have the following prototype for an external library function:

extern "C" DWORD EXPORT FILES_GetMemoryMapping(
  PSTR pPathFile,
  PWORD Size,
  PSTR MapName,
  PWORD PacketSize,
  PMAPPING pMapping,
  PBYTE PagesPerSector);

and in it is used like such:

FILES_GetMemoryMapping((LPSTR)(LPCTSTR)MapFile, &Size, (LPSTR)MapName, &PacketSize, pMapping, &PagePerSector);

Now I'm trying to port the first line over to C# and here is where I'm presented with no clear path.

This is what I've got so far:

[DllImport("Files.DLL")]
public static extern uint FILES_GetMemoryMapping(
    [MarshalAs(UnmanagedType.LPStr)]
    string pPathFile,
    out ushort Size,
    [MarshalAs(UnmanagedType.LPStr)]
    string MapName,
    out ushort PacketSize,
    IntPtr pMapping,
    out byte PagesPerSector);

Now the question is: Is there any good guide out there that tells me a "PSTR pPathFile" should be "[MarshalAs(UnmanagedType.LPStr)] string pPathFile" ... Assuming that is correct?

Or, a that a pointer to a "PMAPPING" struct becomes a "out IntPtr pMapping" ... assuming that is correct?

Any help on this one guys?

A: 

That looks right. The first part of your question (relating to MarshalAs) tells the compiler to convert the managed C# variable into a PSTR. Marshaling in the .NET environment refers to transferring data between the managed and unmanaged environment. These attributes (among several others) tell the compiler how to do it specifically.

The second point indicates that it's going to pass a pointer to the struct. The IntPtr type in .NET is a managed type that's used to hold on to a particular piece of memory. In the .NET world, pointers (generally) don't exist, though there still are reference types. Pointer and handle management is done for us by the CLR. The IntPtr struct is used when marshaling pointers to data structures or primitive types

Adam Robinson
+3  A: 

I have yet to find a good reference on this topic

Here you go.

Oddly, the site is down at the moment, but it's a very good resource for marshalling problems. In the mean time, you can use Archive.net's archive of pinvoke.net at http://web.archive.org/web/20080202041852/http://www.pinvoke.net

Joel Coehoorn
What the frak? I cannot edit this without it getting fucked up.
Samuel
This *valid* url must be screwing up the parser.
Samuel
It chokes on anything with an extra "http://" in it. Known bug.
Joel Coehoorn
A: 

In addition to the P/Invoke site, Adam Nathan's .NET and COM: The Complete Interoperability Guide is something worthwhile adding to your bookshelf if you've more than a passing interest in .NET interop.

Kev

Kev