アンマネージドCに構造体のC ++ / CLIの配列をマーシャリングする方法++

StackOverflow https://stackoverflow.com/questions/734996

質問

私は、アンマネージC ++ DLLに構造体配列を渡すために正しい構文を探しています。

私のdllの輸入は、

このように呼ばれています
    #define _DllImport [DllImport("Controller.dll", CallingConvention = CallingConvention::Cdecl)] static
_DllImport bool _Validation(/* array of struct somehow */);

私のクライアントコードでは、私が持っている

List<MyStruct^> list;
MyObject::_Validation(/* list*/);

私は、System ::ランタイム::にInteropServicesを知っている::元帥はこのようなものを行うための便利な方法をたくさん持っているが、私は使用しているわからないんだけど。

役に立ちましたか?

解決

StructLayout.Sequentialを使用して管理されていない構造体の管理バージョンを作成します(同じ順序で物事を入れてください)。あなたが任意の管理機能(例えば、検証(体mystruct [] pStructs)に渡したいようあなたはそれを渡すことができる必要があります。

たとえば、私たちのネイティブ関数はこのプロトタイプを持っているとしましょう。

extern "C" {

STRUCTINTEROPTEST_API int fnStructInteropTest(MYSTRUCT *pStructs, int nItems);

}

以下のようにネイティブ体mystructに定義される:

struct MYSTRUCT
{
    int a;
    int b;
    char c;
};
次のように

そして、C#では、あなたは、構造体の管理バージョンを定義します:

[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct MYSTRUCT
{
    public int a;
    public int b;
    public byte c;
}

そして管理のプロトタイプは次のよう:

    [System.Runtime.InteropServices.DllImportAttribute("StructInteropTest.dll", EntryPoint = "fnStructInteropTest")]
    public static extern int fnStructInteropTest(MYSTRUCT[] pStructs, int nItems);
次のように

あなたはそれに体mystructの構造体の配列を渡す関数を呼び出すことができます:

    static void Main(string[] args)
    {
        MYSTRUCT[] structs = new MYSTRUCT[5];

        for (int i = 0; i < structs.Length; i++)
        {
            structs[i].a = i;
            structs[i].b = i + structs.Length;
            structs[i].c = (byte)(60 + i);
        }

        NativeMethods.fnStructInteropTest(structs, structs.Length);

        Console.ReadLine();
    }
scroll top