tags:

views:

970

answers:

1

I am trying to pass a structure from C# into C++ library. I pass structure as an object, and C++ function expects it as a pointer (void *).

I am having problem passing the structure.

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

Here is the run-time exception text I get:

"Cannot marshal 'parameter #1': Invalid managed/unmanaged type combination (this value type must be paired with Struct)."

Though I found an MSDN article that uses LPStruct in exactly this context.

This is my structure I'm trying to marshal:

[StructLayout(LayoutKind.Sequential)]
public struct UserRec {
    [MarshalAs(UnmanagedType.I4)]
    public int userParam1;
}

This is C++ function:

MOCKVADAVLIB_API tVDACQ_CallBackRec * TheFunction(void * userParams) {...
+3  A: 

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.

JaredPar
You don't even need the [MarshalAs] in this case I think.
Anton Tykhyy
@Anton, you're correct (updated)
JaredPar
End working result:public static extern IntPtr TheFunction([MarshalAs(UnmanagedType.Struct), In] ref UserRec userRec);And [MurshalAs] here is just to make it explicit, but not required.