使用 C++ 和嵌入式单声道调用 C# DLL 时无法加载程序集系统

Could not load assembly System when using C++ and embedded mono to call to C# DLL

我有一个 C# 示例代码,它使用 Linux 上的 xbuild 编译成 DLL,例如:

using System;
using System.IO;
using System.Collections.Generic;
// ...

namespace MySamples
{
public class MyExample
{
    public static void test()
    {
        SortedSet<int> ss = new SortedSet<int>();
    } 
    // main function calls for test()
}
}

我可以在命令行中使用 xbuild MyExample.csproj 轻松地将示例代码编译成 exedll,然后使用 mono MyExample.exe 运行 - 一切工作正常,示例代码 returns 预期结果。

现在我想从我的 C++ 代码中调用示例代码,特别是 test() 函数。我为此使用了单声道 运行time,这是我的 C++ 代码:

#include <mono/jit/jit.h>
#include <mono/metadata/object.h>
#include <mono/metadata/environment.h>
#include <mono/metadata/assembly.h>
#include <mono/metadata/debug-helpers.h>
#include <mono/metadata/mono-config.h>

// ...
MonoDomain* domain = mono_jit_init("MyExample.dll");
MonoAssembly* assembly = mono_domain_assembly_open(domain, "MyExample.dll");
mono_config_parse("MyExample.dll.config");

// mono is not installed in default locations:
mono_set_dirs("mypath/lib/mono", "mypath/etc/mono");

MonoImage* image = mono_assembly_get_image(assembly);

MonoClass* klass = mono_class_from_name(image, "MySamples", "MyExample");
MonoObject* object = mono_object_new(domain, klass);
mono_runtime_object_init(object);

// call test()
MonoMethodDesc* mdesc = mono_method_desc_new(":test()", false);
MonoMethod* method = mono_method_desc_search_in_class(mdesc, klass);
mono_runtime_invoke(method, object, NULL, NULL);

// shutdown the runtime
mono_jit_cleanup (domain);

C++代码,当运行,returns类型错误:

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=...' or one of its dependencies. ...

因为我知道如果我 运行 通过命令行使用 mono 相同的代码并且它有效,我觉得我的 C++ 代码和我如何设置单声道 运行 时间。我通过添加 mono_set_dirs 修复了一堆其他错误,因为我的 Mono 没有安装到默认目录(它是从源代码构建的)。

我在 Ubuntu 16.04,如果重要的话,mono 是从源代码构建的,CMake 用于编译我的 C++ 代码,MyExample.dll.config 内容:

<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>    
</configuration>

*.csproj 文件按以下方式包含 System

<Reference Include="System" />

再一次,当使用 mono 从命令行(不是从 C++ 项目)使用 运行 test() 和现在的 C# 设置时,我能够 运行 test()。 =32=]

还有一件奇怪的事:如果我用List<int>替换SortedSet<int>,它运行不会抛出任何错误。怎么可能? - they belong to the same namespace。我检查了其他类型,并且在初始化大多数类型时抛出异常。

知道这里出了什么问题吗?我一直在检查 mono embedded docs 以试图找出我的设置可能有什么问题,但这是我所能达到的范围。我是 C#、单声道 运行time 和嵌入式单声道的初学者。

这个问题很简单 - 我搞砸了我的 C++ 代码中的单库路径。显然,您需要提供前缀,而不是完整路径。所以,就我而言,我不得不使用:

mono_set_dirs("mypath/lib", "mypath/etc");

最后没有使用 mono