Skip to content

Instantly share code, notes, and snippets.

@jonpryor
Last active August 29, 2015 14:27
Show Gist options
  • Save jonpryor/f121ba42e12742e172b4 to your computer and use it in GitHub Desktop.
Save jonpryor/f121ba42e12742e172b4 to your computer and use it in GitHub Desktop.
struct B {
int a;
};
struct D {
struct B base;
int d;
};
int
mc_check (struct D *value, int a, int d)
{
if (value->base.a != a)
return 1;
if (value->d != d)
return 2;
return 0;
}
// Marshal Classes
using System;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
class B {
public int a;
}
// Sequential Layout "mirrors" the mc.c `struct D` declaration:
// The members of B are present before the members of D:
[StructLayout(LayoutKind.Sequential)]
class D : B {
public int d;
}
// Explicit layout allows controlling how B is marshaled
[StructLayout(LayoutKind.Explicit)]
class ExplicitD : B {
[FieldOffset(0)] public int a2;
[FieldOffset(4)] public int d2;
}
class App {
[DllImport ("mc")]
public static extern int mc_check (D value, int a, int d);
[DllImport ("mc")]
public static extern int mc_check (ExplicitD value, int a, int d);
public static void Main ()
{
var d = new D {
a = 1,
d = 2,
};
int r = mc_check (d, 1, 2);
Console.WriteLine ("r={0}", r); // r=0
var ed = new ExplicitD {
a = 0,
a2 = 1,
d2 = 2,
};
r = mc_check (ed, 1, 2);
Console.WriteLine ("r={0}", r); // r=0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment