zoukankan      html  css  js  c++  java
  • 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!

  • 相关阅读:
    单点登录学习的教程
    单点登录
    Linux下VI的使用
    伪分布式下的hadoop简单配置
    Linux下配置Java环境变量
    spring mvc 重新定向到一个新的Url
    LeetCode --- 字符串系列 ---“气球” 的最大数量
    http 简述
    dpr 与 移动端 1px 问题
    rem 与 vm 布局
  • 原文地址:https://www.cnblogs.com/night-ride-depart/p/6719691.html
Copyright © 2011-2022 走看看