2011-01-07 27 views
0

我想用C#調用C++函數(在win32.dll中)。 ++函數在像這樣C:使用C++類型編組的類型編組

bool pack(BYTE * messageFields[]); 

功能要填補一些數據在輸入參數的一些索引(例如,字符串或字節[])。 因此請告訴我如何在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

然後,我送的一個維陣列,可容納只有一個系列的字節。但似乎C++函數想要一個2維數組! – losingsleeep 2011-01-07 09:11:53