LoginSignup
3
4

More than 5 years have passed since last update.

Cの構造体を、C#の構造体にマーシャリングしたらメンバの値が正しくなかった

Last updated at Posted at 2015-09-30

やりたいこと

こんなC++の構造体を

struct example {
    int a;
    bool b;
    bool c;
    int d;
    int e;
}:

この構造体にマーシャリングしたい。

[StructLayout(LayoutKind.Sequential)]
struct ExampleCS
{
    public int a;
    public bool b;
    public bool c;
    public int d;
    public int e;
}

問題

C#側で受け取った時に、なんか、値が変わる。困る。

対処

こんな風にした。

[StructLayout(LayoutKind.Sequential)]
struct ExampleCS
{
    public int a;
    [MarshalAs(UnmanagedType.I1)]
    public bool b;
    [MarshalAs(UnmanagedType.I1)]
    public bool c;
    public int d;
    public int e;
}

要は、C#側でboolとして受け取りたいメンバが、ネイティブ側で何バイトなのかを指定しましょう、ということ。

マーシャリング時、C#構造体におけるboolは、ネイティブ(C/C++)側の構造体においてデフォルトでは
(おそらく)4バイトを想定しているんでしょうね。

boolじゃなくてBOOLなんでしょう。

蛇足

そもそもboolのサイズは規定されていない(と思う)ので、
UnmanagedTypeの値は、ネイティブ側の実装に合わせましょう。

考えてみれば当たり前だけど、結構ハマる。

3
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4