2009-04-09 4 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); 

} 
을 다음과 같이

struct MYSTRUCT 
{ 
    int a; 
    int b; 
    char c; 
}; 

그런 다음 C#으로, 당신은 구조체의 관리 버전을 정의 : 다음과 같이

및 기본 MYSTRUCT 정의된다

[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를 사용해야한다고 생각합니다.

관련 문제