2011-01-07 8 views
0

C#으로 C++ 함수 (win32 .dll)를 호출하고 싶습니다. 이런 역할에서 는 C++ :C++ 형식 작업을위한 형식 마샬링

bool pack(BYTE * messageFields[]); 

함수는 일부 데이터를 작성하고자하는 입력 인수 일부에서 인덱스. (예 : 스트링 또는 바이트 []). PLZ에서 마샬링이 C# .NET에 있어야하는 방법을 알려주세요. 나는 많은 유형을 시도했으나 오류가 있거나 매개 변수에 아무런 영향을주지 않았습니다!

C# 코드는 기본 .DLL를 열어야합니다 :

[DllImport("c:\\theDllName.dll")] 
     public static extern bool pack(// what is here?) 

답변

1

System.Byte []를 당신은 아마 찾고있는 것입니다.

죄송합니다. BYTE *를 (를) 가져 왔습니다.

일부 코드

extern "C" UNMANAGEDCPP_API int fnUnmanagedCpp(BYTE* test[], int nRows, int nCols) 
{ 
    //do stuff 
    std::cout << "called!" << std::endl; 

    for (int i = 0; i < nRows; ++i) 
    { 
     for (int j = 0; j < nCols; ++j) 
     { 
      std::cout << int (test[i][j]) << std::endl; 
     } 
    } 

    test[0][0] = 23; 

    return 0; 
} 

그리고 C#에서

:

[DllImport("UnmanagedCpp.dll", CallingConvention=CallingConvention.Cdecl)] 
    public static extern int fnUnmanagedCpp(IntPtr[] buffer, int nRows, int nCols); 

    public static IntPtr[] Marshall2DArray(byte[][] inArray) 
    { 
     IntPtr[] rows = new IntPtr[inArray.Length]; 

     for (int i = 0; i < inArray.Length; ++i) 
     { 
      rows[i] = Marshal.AllocHGlobal(inArray[i].Length * Marshal.SizeOf(typeof(byte))); 
      Marshal.Copy(inArray[i], 0, rows[i], inArray[i].Length); 
     } 

     return rows; 
    } 

    public static void Copy2DArray(IntPtr[] inArray, byte[][] outArray) 
    { 
     Debug.Assert(inArray.Length == outArray.Length); 

     int nRows = Math.Min(inArray.Length, outArray.Length); 

     for (int i = 0; i < nRows; ++i) 
     { 
      Marshal.Copy(inArray[i], outArray[i], 0, outArray[i].Length); 
     } 
    } 

    public static void Free2DArray(IntPtr[] inArray) 
    { 
     for (int i = 0; i < inArray.Length; ++i) 
     { 
      Marshal.FreeHGlobal(inArray[i]); 
     } 
    } 

    static void Main(string[] args) 
    { 
     byte[][] bTest = new byte[2][] { new byte[2] { 1, 2 }, new byte[2] { 3, 4 } }; 

     IntPtr[] inArray = Marshall2DArray(bTest); 

     fnUnmanagedCpp(inArray, 2, 2); 

     Copy2DArray(inArray, bTest); 
     Free2DArray(inArray); 

     System.Console.WriteLine(bTest[0][0]); 
    } 

내가 어쩌면 이렇게 다른 더 나은/간단한 방법이있다,이 도움이되기를 바랍니다. 이 코드는 "일러스트레이션"용이며 버그가있을 수 있습니다.

기본적으로 하나는 IntPtrs의 배열을 통과하고 수동으로 마샬링됩니다.

+0

그러면 일련의 바이트를 저장할 수있는 1 차원 배열을 보냅니다. 그러나 그것은 C++ 함수가 2 차원 배열을 원한다고 보여집니다! – losingsleeep

+0

@ user434186 질문에 대한 답변 중 일부를 '수락'으로 표시 할 수 있습니다. 이렇게하려면 가장 도움이되는 답으로 이동하여 투표 수 아래의 작은 눈금을 클릭하십시오. –

+0

감사합니다 ds27680 ... – losingsleeep