How do I marshal a structure as a pointer to a structure?

Some additional information followup regarding @Rytmis's post.

From https://learn.microsoft.com/en-us/dotnet/standard/native-interop/best-practices#guids:


DO NOT Use [MarshalAs(UnmanagedType.LPStruct)] for anything other than ref GUID parameters.


Try passing the structure as a ref parameter.

[DllImport("MockVadavLib.dll", CharSet = CharSet.Ansi)]
public static extern IntPtr TheFunction(ref UserRec userRec);

When you use a ref combined with a structure, it conceptually passes the address.


Incidentally, UnmanagedType.LPStruct is rarely, if ever, the correct MarshalAs argument. A quote from Adam Nathan who is a Microsoft employee:

UnmanagedType.LPStruct is only supported for one specific case: treating a System.Guid value type as an unmanaged GUID with an extra level of indirection.

Tags:

C#

Pinvoke