Search code examples
c#cdllstructpinvoke

How to use pinvoke to marshall structure inside another passed to C DLL


I am trying to figure out how to embed a simple structure inside another structure that is passed to a C dll from c#. How do you marshall the embedded structure? Stripped down to essentials.

//The C code
typedef struct {
       int a;
       int b;
} A;
typedef struct {
      int c;
      A myStruct;
} B;

//The c# code:
using System.Runtime.InteropServices;

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public class A{
        int a;
        int b;
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public class B{
          int c;
          public IntPtr A;
     }

Solution

  • [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public class B{
          int c;
          public A a;
        }
    

    You need IntPtr only if B is defined as:

    typedef struct {
          int c;
          A* myStruct;
    } B;