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

前端 未结 3 505
自闭症患者
自闭症患者 2021-01-11 18:36

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 pas

相关标签:
3条回答
  • 2021-01-11 19:10

    Some additional information followup regarding @Rytmis's post.

    From https://github.com/dotnet/runtime/blob/master/docs/coding-guidelines/interop-pinvokes.md:


    Guids are usable directly in signatures. When passed by ref they can either be passed by ref or with the [MarshalAs(UnmanagedType.LPStruct)] attribute.

    [MarshalAs(UnmanagedType.LPStruct)] should only be used for by ref Guids.

    0 讨论(0)
  • 2021-01-11 19:29

    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.

    0 讨论(0)
  • 2021-01-11 19:32

    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.

    0 讨论(0)
提交回复
热议问题