C ++到.net字典,得到了MarshalDirectiveException

时间:2015-08-24 12:05:39

标签: c# c++ exception dictionary

我有一个cpp项目(创建test.DLL)和一个C#win表单项目(使用test.DLL)。如何将C ++字典转换为.net dictonary?

我尝试使用此代码,但我得到unhandled exception类型System.Runtime.InteropServices.MarshalDirectiveException

DLL cpp项目

Dictionary<int, int>^ TestDictionaryElements()
{
    Dictionary<int, int>^ h_result = gcnew Dictionary<int, int>();

    h_result->Add(1, 2);

    return (h_result);
}
extern "C"
{
     Dictionary<int, int>^ TestDic()
     {
         Dictionary<int, int>^ dic_result = TestDictionaryElements();
         return dic_result;
     }
}

C#win表单项目

class Program
{
    [DllImport("test.dll")]
    public static extern Dictionary<int, int> TestDic();
    static void Main(string[] args)
    {
        Dictionary<int, int> resulDic = TestDic();
    }
}

1 个答案:

答案 0 :(得分:2)

在您的cpp项目中,您已经使用了托管C ++(CLI)因此您不必导出某些东西。您可以直接引用托管c ++ dll。然后你可以调用&#34; TestDictionaryElements&#34;直。不需要DllImport。

要访问CLI代码,您应该创建一个包含代码的公共类:

<强> CPP

public ref class TestDictionary
{
public:

    Dictionary<int, int>^ TestDictionaryElements()
    {

        Dictionary<int, int>^ h_result = gcnew Dictionary<int, int>();

        h_result->Add(1, 2);

        return (h_result);
    }
}

<强> c#中

    class Program
{
    static void Main(string[] args)
    {
        TestDictionary testDict = new TestDictionary();
        var result =testDict.TestDictionaryElements();
    }
 }