Marshal

※前提条件:本情報はOpenCV3.1を基づいて説明してる

C++側は以下のようにstructを宣言する

extern "C" {

struct MyStruct
{
    char* id;
    char* description;
};
}

C++側は以下のようにstructを返すメソッドを作成する

__declspec(dllexport)
MyStruct* __stdcall get_my_structures()
{
    static MyStruct a[] =
    {
        { "id1", "desc1" },
        { "id2", "desc2" },
        { "id3", "desc3" }
    };
    return a;

}

C#側は以下のように呼び出し取得する

using System;
using System.Runtime.InteropServices;


[StructLayout(LayoutKind.Sequential)]  
public class MyStruct
{
  [MarshalAsAttribute(UnmanagedType.LPStr)]
  public string _id;
  [MarshalAsAttribute(UnmanagedType.LPStr)]
  public string _description;
}


class Program
{
    [DllImport("dll")]
    static extern IntPtr get_my_structures();

    static void Main()
    {
        int structSize = Marshal.SizeOf(typeof(MyStruct));
        Console.WriteLine(structSize);

        IntPtr myStructs = get_my_structures();
        for (int i = 0; i < 3; ++i)
        {
            IntPtr data = new IntPtr(myStructs.ToInt64() + structSize * i);
            MyStruct ms = (MyStruct) Marshal.PtrToStructure(data, typeof(MyStruct));

            Console.WriteLine();
            Console.WriteLine(ms._id);
            Console.WriteLine(ms._description);
        }
    }
}

配列内要素の個数の取得に、いい方法がなく、現在Structの中にsize変数を用意して、C#側ではそれを取得してから利用する方法で実現する。



超多機能のアクセス解析が永久無料!

コメント:



(画像の文字列を入力して下さい)

トップ   編集 凍結 差分 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2019/12/02 (月) 12:33:34 (1627d)

yVoC[UNLIMITȂ1~] ECirŃ|C Yahoo yV LINEf[^[Ōz500~`I


z[y[W ̃NWbgJ[h COiq 萔O~ył񂫁z COsیI COze