【问题标题】:type marshaling for working with C++ types用于处理 C++ 类型的类型封送处理
【发布时间】:2011-01-07 08:56:15
【问题描述】:

我想通过 C# 调用一个 c++ 函数(在 win32 .dll 中)。 c++中的函数是这样的:

bool pack(BYTE * messageFields[]);

函数想要在输入参数的某些索引处填充一些数据(例如字符串或字节[])。 所以请告诉我在 C#.NET 中应该如何编组?我尝试了多种类型,但出现错误或对我的参数没有影响!

C# 代码必须打开原生 .DLL:

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

【问题讨论】:

    标签: c# c++ winapi dll marshalling


    【解决方案1】:

    System.Byte[] 是您可能正在寻找的。​​p>

    抱歉没有看到您有 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 数组并手动编组...

    【讨论】:

    • 然后,我发送一个只能容纳一系列字节的一维数组。但似乎 C++ 函数想要一个二维数组!
    • @user434186,您可能希望将您的问题的一些答案标记为“已接受”。为此,请转到您认为最有帮助的答案,然后点击投票数下方的小勾号。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多