簡體   English   中英

使用C ++和嵌入式Mono調用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運行-一切正常,示例代碼返回預期結果。

現在,我想從我的C ++代碼中調用示例代碼,尤其是test()函數。 我為此使用了單聲道運行時,這是我的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 ++代碼在運行時返回錯誤類型:

未處理的異常:System.IO.FileNotFoundException:無法加載文件或程序集'System,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = ...'或其依賴項之一。 ...

因為我知道如果我通過命令行使用mono運行相同的代碼並且可以正常工作,那么我感覺C ++代碼以及如何設置Mono運行時存在問題。 由於我的Mono未安裝到默認目錄(它是從源代碼構建的)中,因此我通過添加mono_set_dirs修復了許多其他錯誤。

我在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" />

再一次,當我從命令行(而不是從C ++項目)使用mono和現在的C#設置時,我能夠運行test()

這是另外一件奇怪的事情 :如果我用List<int>替換SortedSet<int> List<int> ,它將運行而不會引發任何錯誤。 怎么可能? - 它們屬於同一名稱空間 我檢查了其他類型,並在初始化大多數類型時引發了異常。

有什么主意在這里嗎? 我一直在檢查單聲道嵌入式文檔,以嘗試找出設置方面的問題,但這是我所能及的。 我是C#,Mono運行時和嵌入式Mono的初學者。

問題是如此的微不足道-我在C ++代碼中弄亂了mono lib路徑。 顯然,您需要提供一個前綴,而不是完整路徑。 因此,就我而言,我必須使用:

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

最后不使用mono

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM