多语言展示
当前在线:1814今日阅读:27今日分享:41

C#调用C 的DLL的方法

我们在用c#开发时,有时后需要用到c语言开发的DLL库,有时候项目中有些东西需要c语言来做,有些东西需要C#来做,那么我们如何使用C#来调用c语言的DLL库呢
工具/原料

VS

方法/步骤
1

首先我们新建一个C语言的WIN32项目,在选择项目时,要选择项目类型为DLL库

2

在新建的项目中我们添加testC.h,testC.cpp两个文件extern "C"  __declspec(dllexport) int delx(int a, int b);extern "C"  __declspec(dllexport) int add(int a, int b);#include"testC.h"int delx(int a, int b){ return a - b;}int add(int a, int b){ return a + b;}

3

然后编译生成DLL,注意我们要知道设置DLL文件的输出目录,右键,属性,可以看到输出目录选项,这时就可以设置输出目录,编译后就可以在文件夹中找到testC.dll

4

这时候在新建一个C#的控制台输出程序,如图

5

在生成的Program.cs中添加如下代码,其中DllImport是引入C的DLL,CallingConvention是调用程序的约定,add和delx是C中函数的名字,注意名字一定要一样啊using System;using System.Collections.Generic;using System.Linq;using System.Runtime.InteropServices;using System.Text;using System.Threading.Tasks;namespace testCDll{    class Program    {        static void Main(string[] args)        {            Console.WriteLine(testCDLL.delx(5, 3));            Console.WriteLine(testCDLL.add(3, 5));                      Console.ReadKey();        }    }   public  class testCDLL    {        [DllImport("testC.DLL" , CallingConvention = CallingConvention.Cdecl )]        public static extern int add(int a,int b);        [DllImport("testC.DLL",CallingConvention = CallingConvention.Cdecl)]       public static extern int delx(int a, int b);    }}

6

然后编译生成,将C的DLL文件拷贝到C#程序的可执行目录下,程序就可以正常运行了。或者,将两个程序的生成目录设置为同一目录,程序也可以正常运行。如图

7

现在就完成了C#对C的DLL的调用,如果还有什么问题,欢迎给我留言。

注意事项
1

注意函数的名字要一样啊

2

注意程序的目录要一样啊

3

注意别忘了dllexport和dllimport啊

推荐信息