C#调用C语言生成的DLL示例

完成这件事情需要做几个准备,如下:

 

Ÿ  编写C源文件;

Ÿ  找到VS下的C编译器 cl.exe link.exe;

Ÿ  编写C#调用dll代码;

 

-----------------------------------------------------------------------------------------

  1. 编写C源文件:

举如下例子:

a)     在记事本中编写如下代码,并另存为 hello.c;

#include "stdio.h"

__declspec(dllexport) char* Hello()

{

           return "Hello World!";

}

 

  1. 找到VS下的C编译器 cl.exe link.exe;

a)     编译器一般在VS安装目录的VC文件夹下,不过我们不需要这么麻烦。我们只需要打开开始菜单VS目录下的 “Visual Studio Tools”文件夹,选择“Visual Studio 命令提示(2010)”,就会打开一个VS命令提示窗体,如图:

b)     输入命令开始编译

c)      可以在源代码文件夹下看到编译好的dll文件

  1. 编写C#调用dll代码;

a)     新建一个C#项目(WinForm、控制台都可以);

b)     把hello.dll拷贝到c#项目Debug文件夹下。

c)      在需要调用dll的地方执行如下代码(记得引用using System.Runtime.InteropServices;):

[DllImport("hello.dll")]

public extern static string Hello();

private void button1_Click(object sender, EventArgs e)

{  

  string str=hello().ToString ();
  MessageBox.Show(str);

}

 

 

posted @ 2012-07-29 13:52  南山砍柴的  阅读(2133)  评论(0编辑  收藏  举报