NET的程序是和Java一样的托管代码,在底层操作上,具有很大的局限性,像Java的JNI一样,.NET具有Platform Invoke(平台调用,通常叫P/Invoke)。本文中,Linux下的.NET托管代码运行在Mono CLR上。之所以做跨平台的P/Invoke,是因为考虑到有些客户在Win32/WinCE等系统中开发的.NET程序,需要换到Linux平台运行。嵌入式开发中,经常需要操作IO,.NET程序就通过P/Invoke来调用一些用比如c/c++一类语言开发的native代码完成IO操作。这时候针对windows编写的native代码,就不能不加修改的移植到Linux上,要完成这个移植工作就需要编写Linux下的native代码。但如何做到不修改.NET程序呢,下面就让笔者以实例讲述。r 要保证.NET程序不加修改,不许重新编译,需要做到native代码具有一致的接口。比如我们有native.dll何libnative.so两个不同系统下的动态链接库,在.NET程序中,调用动态库中的getSum(int a,int b)函数,则需要在native.dll和libnative.so中都存在getSum(int a, int b)函数,而且导出的名字要一致,都是getSum。编译时要注意编译器对符号名称的修饰,vc编译器中,可以用Module-Defination File(.def)文件来规范到处的函数名称。r 在.NET的代码中,透过DllImport引入外部函数时,指定的链接库模块不要加扩展名。比如native.dll,只要写native就好。windows中,会自动寻找native.dll,Linux下对应的是libnative.so。r 以下是实例代码:r using System;r using System.Runtime.InteropServices;r namespace Managedr {r class Programr {r r public static extern int getSum(int a, intb);r r static void Main(string args)r {r System.Console.WriteLine("Managed code out.");r System.Console.WriteLine("1+2=" + getSum(1, 2));r }r }r }r 上边的代码演示了从外部动态链接库引入函数的方式,注意没有加扩展名。接下来在看看windows下的c代码是如何编写的:r /**r * native.h 头文件,声明函数原型r */r #ifndef NATIVE_Hr #define NATIVE_Hr #ifdef __cplusplusr extern "C" {r #endifr int __stdcall getSum(const int a, const intb); // 原型r #ifdef __cplusplusr }r #endifr #endifr r /*r * native.cppr * 2013-03-05 实现功能的代码r */r #include "native.h"r #include