且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

测试 Mono 安装

更新时间:2022-09-05 14:04:28

测试 Mono 安装

为了测试核心编译器(mcs)和运行时(mono),应该创建一个简单的程序并编译它。可以在喜欢的任何文本编辑器中创建程序。这里采用一种快速而简陋的方法创建该文件(虽然没有任何格式化),从终端提示符中运行下列命令(都在一行中):

$ echo 'class X { static void Main () { System.Console.Write("My first          mono app worked!\n");} }' > example.cs

该命令创建一个名为 example.cs 的 C# 源文件(也可从下面的 下载 部分下载该文件 example.cs 和可执行文件 example.exe。(注意,如果使用 Linux 可直接使用 bash 提示符,如果使用 Windows 则需要从开始菜单中调用 Mono 命令提示符。)

要测试编译器创建可执行文件的能力,可输入下面的命令:

$ mcs example.cs

这样将生成名为 example.exe 的二进制文件。要运行它来测试运行时,可使用该命令:

$ mono example.exe

如果一切正常,就会在控制台中看到“My first mono app worked!”字样。

图 1. 正常运行的结果

测试 Mono 安装

 

事实上,可以将得到的可执行文件复制到其他系统上,比如运行 Windows 的系统上,无需修改就可以执行。

 

使用非 Mono 库的代码

使用 Mono 平台更有说服力的原因是能够使用已有的、可能不属于 C# 库的 C# 代码。下面是这样的一个例子(也可以从下面的 下载 部分下载清单 2 PInvokeExample.cs 和可执行文件 PInvokeExample.exe)。

提供这种能力的机制是 Platform Invocation Facility(缩写为 pinvoke)。

清单 2. 使用 Platform Invocation Facility
/* Platform Invocation Facility Example
   This code is intended to illustrate P/Invoke.
   For out purposes we will access a c shared library.
*/
using System;
// This is a lot of the magic!
using System.Runtime.InteropServices;
/* Class illustrates pinvoking existing c library code */
public class PInvokeExample
{
   /* Notifying the runtime that we need an
          additional mathematics library, libm.so */
   [DllImport("libm")]
   /* Here we define the external function we will
           be using from the library,
           You must declare these methods to be static.
      The function signature you provide must match the
           signature in the external library!
   */
        static extern double sqrt ( double element );
   public static void Main ()
   {
      Console.WriteLine("The square root of 100.0 is {0}.", sqrt(100.0));
   }
}

从上述简化的代码中可以看出,只需要告诉 Mono 编译器使用什么库(在 DLLImport 一行中完成)并提供要使用的函数的原型。如果在 Linux 系统上编译这个类,控制台将显示正确的结果。

本文转自jiahuafu博客园博客,原文链接http://www.cnblogs.com/jiahuafu/p/4013104.html如需转载请自行联系原作者


jiahuafu