使用C ++ / CLI包装器将结构数组从C#传递到C ++

时间:2018-04-11 13:03:57

标签: c# c++ arrays c++-cli marshalling

我正在一个需要优化C#代码的项目中工作,因此我将代码转换为C ++并且这样做,我使用的是C ++ / CLI包装器,它作为托管C#和非托管C ++之间的桥梁。 。我试图与两者进行沟通,但由于我对这个主题很新,所以它不起作用。我一直在寻找和搜索,但仍保持不变。

我希望在本机C ++中拥有与C#相同的结构数组,这是实现目标的主要目标。

我的C#代码“ConsoleApp1”如下:

namespace ConsoleApp1
{
    class Program
    {
        // Struct definition
        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        public struct MyStruct
        {
            [MarshalAs(UnmanagedType.LPWStr)]
            public int a;

            [MarshalAs(UnmanagedType.LPWStr)]
            public int b;

            public MyStruct(int a, int b)
            {
                this.a = a;
                this.b = b;
            }
        };

        static void Main(string[] args)
        {
            UnmanagedWrap.Class1 test = new UnmanagedWrap.Class1();

            // Instantiating struct and initializing
            MyStruct str1 = new MyStruct(4, 5);
            MyStruct str2 = new MyStruct(6, 7);

            // Array of structs
            MyStruct[] MyArray = new MyStruct[] { str1, str2 };

            // Calling C++/CLI method passing the struct
            test.Foo(MyArray, MyArray.GetLength);

            Console.ReadKey();
        }
    }
}

然后我的C ++ / CLI包装器名为UnmanagedWrap:

namespace UnmanagedWrap {

    public ref class Class1
    {
    public:

        // pointer to the Unmanaged class
        Unmanaged * pu;  

        // the constructor will allocate the pointer pu
        Class1() : pu(new Unmanaged()) {};      

        void Foo(array<MyStruct^>^ configObject, int ArrayLength) {

            // Allocates memory from the unmanaged memory of the process by using the specified number of bytes.
            // Between brackets is the required number of bytes in memory.
            IntPtr ptr = Marshal::AllocHGlobal(Marshal::SizeOf(configObject));

            // Marshals data from a managed object to an unmanaged block of memory. 
            // ptr is a pointer to an unmanaged block of memory, which must be allocated before this method is called.
            Marshal::StructureToPtr(configObject, ptr, false);

            pu->Foo(ptr);
        };
    };

    public ref struct MyStruct {
        int a;
        int b;
    };
}

我的非托管C ++ Unmanaged.h:

#pragma once
class Unmanaged
{
public:

    struct MyUnmanagedStruct {
        int var1, var2;
    };

    void Foo(MyUnmanagedStruct* d);
};

和Unmanaged.cpp:

#include "stdafx.h"
#include "Unmanaged.h"

void Unmanaged::Foo(MyUnmanagedStruct* ustr) {
    int x = ustr->var1;
    int y = ustr->var1;
}

由于从C ++ / CLI到C ++的调用函数类型不匹配,此过程不起作用,但即使我经常查找它,我也不知道如何以正确的方式执行此操作。

0 个答案:

没有答案