使用C++类型编组的类型编组

问题描述:

我想用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?) 

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