C#调用C 的DLL的方法

2025-11-04 22:39:36

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

C#调用C 的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;

}

C#调用C 的DLL的方法

C#调用C 的DLL的方法

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

C#调用C 的DLL的方法

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

C#调用C 的DLL的方法

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);

    }

}

C#调用C 的DLL的方法

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

如图

C#调用C 的DLL的方法

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

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢