在C#中调用C/C++代码
示例1: HelloWorld程序
using System.Runtime.InteropServices;
class MyClass
{
[DllImport("User32.dll")]
public static extern int MessageBox(int h, string m, string c, int type);
public static int Main()
{
MessageBox(0, "HelloWorld", "A Message Box", 0);
return 0;
}
}
运行这个程序会弹出一个 HelloWorld 的对话框, 效果和 Windows程序设计 上那个一样. 这段代码用到了两个技术: 一个是extern关键字,一个是 DllImportAttribute 属性.
extern用来修饰一个函数, 表示这个函数在类的外部实现. DllImportAttribute 属性引入一个DLL库,指示该属性化方法由非托管动态链接库 (DLL) 作为静态入口点公开, 通常跟extern一起使用. 用DllImportAttribute 属性时别忘了命名空间System.Runtime.InteropServices
示例2: 调用C/C++代码的具体步骤
被调用的C/C++代码
int __declspec(dllexport) MyMethod(int i)
{
return i*10;
}
(1)将 called.cpp 编译成 dll 文件
命令格式: cl /LD /MD called.cpp
(2) 用C#调用 MyMethod 函数
using System.Runtime.InteropServices;
public class MyClass
{
[DllImport("called.dll",
EntryPoint="MyMethod",
CharSet=CharSet.Unicode,
CallingConvention=CallingConvention.StdCall)]
]
public static extern int ExternMethod(int x);
public static void Main()
{
Console.WriteLine("Externally Called MyMethod() returns {0}.", ExternMethod(5));
}
}
其中EntryPoint是外部函数的入口点, 在 这里是“MyMethod“.
好了现在运行这个程序,结果是不是调用了 MyMethod, 呵呵. 当然了,这只是个很小的Demo, 并没有很全面的讲解实际运作中会遇到的所有问题, 比如, C/C++ 与 C# 类型转换, C/C++没有内置string类型那. 等等. 不过麻雀虽小,五脏俱全,大体的调用框架是有了. 哈.
要求和注意问题:调用的C/C++代码必须是普通函数或静态函数, 不能是类的函数成员. C#中的extern函数只能是静态的.