1 // case 1 传递 int* ///////////////////////////////////////////// 2 extern “C” __declspec(dllexport) int mySum(int *a2,int *b2) 3 { 4 // 改变 a1, b1 5 *a2=... 6 *b2=... 7 return a+b; 8 } 9 public static extern int mySum (ref int a1,ref int b1); // c# 声明 10 ///////////////////////////////////////////////////////////////////// 11 12 // case 2 DLL 传入 char* 打印 ///////////////////////////////////////////// 13 extern “C” __declspec(dllexport) void print(const char *str) 14 { 15 printf(str); 16 } 17 public static extern void print(string str); // c# 声明 18 ///////////////////////////////////////////////////////////////////// 19 20 // case 3 传入 char* 写回 /////////////////////////////////////////// 21 void foo(char* bar) { 22 // do write some information into char* bar 23 } 24 25 [DllImport("foobar.dll")] 26 private static external void foo(StringBuilder bar); 27 28 public String ReadFoo() { 29 StringBuilder result = new StringBuilder(256); 30 foo(result); 31 return result.ToString(); 32 } 33 // 一些字符的处理 34 public String ReadFoo2() { 35 StringBuilder strBuilder = new StringBuilder(256); 36 foo(strBuilder); 37 Byte[] buf = Encoding.Unicode.GetBytes(strBuilder.ToString()); 38 String result = Encoding.ASCII.GetString(buf); 39 } 40 ///////////////////////////////////////////////////////////////////// 41 42 // case 4 输入数组 //////////////////////////////////////////////// 43 [DllImport("foobar.dll")] 44 private unsafe static extern void getpicture(byte* imageBuffer); 45 46 private byte[] GetImage() { 47 // size of the picture is 1024 * 1024 at RGB color, 8 bit each color 48 Byte[] rc = new Byte[1024 * 1024 * 3]; 49 50 // this block contains unsafe code!!! 51 unsafe { 52 // create the pointer by disabling garbage collection and 53 // memory reallocation 54 fixed (byte* rcPrt = rc) { 55 this.getpicture(rcPtr); 56 } 57 // devalidate pointer and reenable memory reallocation and 58 // garbage collection 59 } 60 // and get safe again 61 62 return rc; 63 } 64 /////////////////////////////////////////////////////////////////
参考:https://www.gadgetweb.de/programming/38-cs-and-the-char-mess.html
时间: 2024-10-11 11:59:29