c# 调用 c dll 例子

 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

注意:结构体中不可以存在方法或者构造函数等其他一切,也就是说只包含成员变量。因为c++的struct如果包含了这些的话,组织结构就会发生异变,与c不同。而c#只单纯处理c的struct!

转载于:https://www.cnblogs.com/night-ride-depart/p/6719691.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值