【问题标题】:C++ to .net dictionary, got MarshalDirectiveExceptionC++ 到 .net 字典,得到 MarshalDirectiveException
【发布时间】:2015-08-24 12:05:38
【问题描述】:

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

我尝试了这段代码,但我得到了 System.Runtime.InteropServices.MarshalDirectiveException 类型的 unhandled exception

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();
    }
}

【问题讨论】:

  • @user1810087 这是 C++/CLI。

标签: c# c++ exception dictionary


【解决方案1】:

在您的 cpp 项目中,您已经使用托管 C++ (CLI) 因此您不必导出某些内容。您可以直接引用您的托管 c++ dll。然后你可以直接调用“TestDictionaryElements”。不需要 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();
    }
 }

【讨论】:

  • 当我直接引用托管 c++ dll 时,出现错误A reference to test.dll couldn't not be added. Please make sure that the file is accessible, and that it is a valid assembly or COM component
  • 公开 dict。只能访问公共对象。
  • 您使用公共语言运行时支持 (/clr) 编译了“test.dll”,对吗?
  • @Manuel。您的示例代码没问题。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2020-02-19
  • 1970-01-01
  • 1970-01-01
  • 2021-10-03
  • 2018-09-05
  • 1970-01-01
  • 2011-10-16
  • 1970-01-01
相关资源
最近更新 更多