2009-04-09 49 views
1

構造体配列をアンマネージC++ dllに渡す正しい構文を探しています。 構造体のC++/CLI配列をアンマネージC++にマーシャリングする方法

私のdllの輸入

は、私は、システム::ランタイム::にInteropServicesを知っている::元帥がために有用な方法をたくさん持っている私は

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

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

#define _DllImport [DllImport("Controller.dll", CallingConvention = CallingConvention::Cdecl)] static 
_DllImport bool _Validation(/* array of struct somehow */); 

のように呼ばれていますこのようなものをやっているが、私はどちらを使うべきかについてはわからない。

答えて

3

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(); 
    } 
1

Marshall.StructureToPtrを使用して、ネイティブのMyStruct *配列に渡すことのできるIntPtrを取得できます。

しかし、これをリストから直接行う方法がわかりません。私はあなたがこれを配列に変換し、ネイティブコードに渡す前に、(GCがあなたのメモリを動かさないように)pin_ptrを使う必要があると信じています。

関連する問題