代码之家  ›  专栏  ›  技术社区  ›  Eric

如何将结构体的C++/CLI数组封送到非托管C++

  •  1
  • Eric  · 技术社区  · 16 年前

    我正在寻找将结构数组传递给非托管C++dll的正确语法。

    我的dll导入的调用方式如下

        #define _DllImport [DllImport("Controller.dll", CallingConvention = CallingConvention::Cdecl)] static
    _DllImport bool _Validation(/* array of struct somehow */);
    

    在我的客户端代码中,我有

    List<MyStruct^> list;
    MyObject::_Validation(/* list*/);
    

    我知道System::Runtime::InteropServices::Marshal有很多有用的方法来做这样的事情,但我不确定该使用哪种方法。

    2 回复  |  直到 16 年前
        1
  •  3
  •   Shea    16 年前

    extern "C" {
    
    STRUCTINTEROPTEST_API int fnStructInteropTest(MYSTRUCT *pStructs, int nItems);
    
    }
    

    并且天然MYSTRUCT定义如下:

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

    [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);
    

        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();
        }
    
        2
  •  1
  •   Reed Copsey    16 年前

    您可以使用 Marshall.StructureToPtr 以获取可以传递到本机MyStruct*数组中的IntPtr。

    推荐文章