[楼主] Linux下给C#增加CopyMemory支持 1、编写C程序,用string.h里面的memcpy函数实现CopyMemory 将下面代码保存为 kernel32.c C++代码 #include<stdio.h> #include<string.h> void CopyMemory(void * src,void * dest,int size) { memcpy(dest,src,size); } int TestAdd(int a,int b) { return a+b; } int TestMin(int a,int b) { return a-b; } int TestMul(int a,int b) { return a*b; } 2、编译成so文件 gcc -Wall -fPIC -c -O2 -o kernel32.o kernel32.c gcc -shared -Wl,-soname,kernel32.so -o kernel32.so kernel32.o 3、在C#里面应用 将下面代码保存为Test.cs C#代码 using System; using System.Runtime.InteropServices; namespace eGlic.Test { public class TestSO { [DllImport("kernel32.so",EntryPoint="TestAdd")] public static extern int TestAdd(int a,int b); [DllImport("kernel32.so",EntryPoint="TestMin")] public static extern int TestMin(int a,int b); [DllImport("kernel32.so",EntryPoint="TestMul")] public static extern int TestMul(int a,int b); [DllImport("kernel32.so",EntryPoint="CopyMemory")] public static extern void CopyMemory(System.IntPtr a,System.IntPtr b,int c); public unsafe static void Main() { int a=4; int b=6; int x=0; x=TestAdd(a,b); System.Console.WriteLine("TestAdd(4,6) ="+x.ToString()); x=TestMin(a,b); System.Console.WriteLine("TestMin(4,6) ="+x.ToString()); x=TestMul(a,b); System.Console.WriteLine("TestMul(4,6) ="+x.ToString()); byte [] d=new byte[4]; a=0x12345678; System.Console.WriteLine("Test CopyMemory......"); System.Console.WriteLine(" >Before CopyMemory: a= 0x"+a.ToString("x")); System.Console.WriteLine(" >Before CopyMemory: d[]= "+d[0].ToString("x")+" "+d[1].ToString("x")+" "+d[2].ToString("x")+" "+d[3].ToString("x")+" "); IntPtr ax; IntPtr dx; int* ap=&a; fixed(byte* dp=&d[0]) { ax=(IntPtr)ap; dx=(IntPtr)dp; CopyMemory(ax,dx,4); } System.Console.WriteLine(" >After CopyMemory: a= 0x"+a.ToString("x")); System.Console.WriteLine(" >After CopyMemory: d[]= "+d[0].ToString("x")+" "+d[1].ToString("x")+" "+d[2].ToString("x")+" "+d[3].ToString("x")+" "); } } } 4、编译测试 mcs -unsafe Test.cs mono Test.exe 结果如下: TestAdd(4,6) =10 TestMin(4,6) =-2 TestMul(4,6) =24 Test CopyMemory...... >Before CopyMemory: a= 0x12345678 >Before CopyMemory: d[]= 0 0 0 0 >After CopyMemory: a= 0x12345678 >After CopyMemory: d[]= 78 56 34 12 | |