测试篇 学习Mono,跨平台c#(半成品)
首先第一個問題是java會提供一個虛擬機,然后c#的虛擬機在哪里呢?
眾所周知的面試題,在clrruntime...What?公共語言運行時...這個爛名字....為什么起這個爛名字,因為微軟避開"虛擬機"這個緩慢意思的詞..
回到問題來,那么unity3d的它的跨平臺服務的c#腳本虛擬機呢?
然后搜了一下,就很容易找到一個關鍵字"mono",它可以讓net嵌入到exe,一種跨平臺的實現了..
具體看這篇文章.NET和JAVA的跨平臺,我們很期望,其實不容易
那么mono的教程....找了半天,發現沒有什么教程.......
唯一可用的教程是這里:
https://blog.csdn.net/zouwei678/article/details/54908687
https://blog.csdn.net/zouwei678/article/details/54909403
但是他的例子有點過時, 我在win10下用vs2019, 用的是mono-6.12.0.98-x64-0.msi
mono下載地址:http://www.mono-project.com/download/
64位安裝完成后將在: C:Program FilesMono
32位安裝完成后將在: C:Program Files (x86)Mono
安裝了之后設置環境
寫一個 Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MonoCsharp
{
public static class MainTest
{
static void Main()
{
System.Console.WriteLine("你好,世界");
System.Console.Read();
}
}
}
View Code
然后在這個文件的文件夾上面用powersell, 輸入下面的,編譯成DLL....路徑可以先忽略
mcs Program.cs -t:library
一、新建c++工程并依賴,項目路徑全英文!!!
二、根據下載的mono的版本,設置編譯生成的目標位X64 或 X86
三、設置包含路徑、庫目錄路徑、附加依賴項
include:
C:Program FilesMonoincludemono-2.0
lib:
C:Program FilesMonolib
附加依賴項
mono-2.0.lib 原博客寫的是這個,
mono-2.0-sgen.lib 但是我下載了的新版本是要這個
四、寫C++代碼,記得修改一下c#的dll路徑..
// MonoDemo.cpp : 此文件包含 "main" 函數。程序執行將在此處開始并結束。
//
#include <iostream>
#include <mono/jit/jit.h>
#include <mono/metadata/assembly.h>
#include <mono/metadata/class.h>
#include <mono/metadata/debug-helpers.h>
#include <mono/metadata/mono-config.h>
MonoDomain* domain;
int main()
{
// Program.cs所編譯dll所在的位置
const char* managed_binary_path = "D:/MonoDemo/x64/Debug/Program.dll";
//獲取應用域
domain = mono_jit_init("Test");
//加載程序集ManagedLibrary.dll
MonoAssembly* assembly = mono_domain_assembly_open(domain, managed_binary_path);
MonoImage* image = mono_assembly_get_image(assembly);
// =====================================================準備調用
//獲取MonoClass,類似于反射
MonoClass* main_class = mono_class_from_name(image, "MonoCsharp", "MainTest");
//獲取要調用的MonoMethodDesc,主要調用過程
MonoMethodDesc* entry_point_method_desc = mono_method_desc_new("MonoCsharp.MainTest:Main()", true);
MonoMethod* entry_point_method = mono_method_desc_search_in_class(entry_point_method_desc, main_class);
mono_method_desc_free(entry_point_method_desc);
//調用方法
mono_runtime_invoke(entry_point_method, NULL, NULL, NULL);
//釋放應用域
mono_jit_cleanup(domain);
return 0;
}
View Code
五、運行會出現這樣的報錯
The assembly mscorlib.dll was not found or could not be loaded.
It should have been installed in the `D:MonoDemox64libmono4.5mscorlib.dll' directory.
這個時候只需要C:Program FilesMonolib拷貝到D:MonoDemo{你的工程}x64lib
一定要注意,{你的工程}的項目路徑一定不能有中文,因為這個東西支持不好......
總結
以上是生活随笔為你收集整理的测试篇 学习Mono,跨平台c#(半成品)的全部內容,希望文章能夠幫你解決所遇到的問題。