c#调用C++ DLL文件

2025-10-27 12:24:24

1、首先打开vs2013(其他版本也可以),在C++项目中选择 Win32程序,然后在控制台程序或者win32程序任选一个。 写上项目名字点创建。(本例用VS2013系统默认项目名,路径随意。)

c#调用C++ DLL文件

c#调用C++ DLL文件

2、选“空项目”建一个计较干净的DLL程序。

c#调用C++ DLL文件

c#调用C++ DLL文件

3、创建项目,这样我们得到一个空项目,在这个项目中,除了几个文件加以外什么也没有,我们在文件夹上点右键,创建新项。在新项里面分别创建一个CPP文件和一个def文件。

c#调用C++ DLL文件

c#调用C++ DLL文件

c#调用C++ DLL文件

4、在“.def”文件中添加代码:

LIBRARY

EXPORTS

  mySum

在“.cpp”文件中添加代码:

//宏定义  

#define LIBEXPORT_API extern "C" __declspec(dllexport)

//设置函数  

LIBEXPORT_API int __stdcall mySum(int a, int b)

{

return a + b;

}

c#调用C++ DLL文件

c#调用C++ DLL文件

5、编译C++ DLL文件,找到编译好的.dll文件,并放到C#程序目录下。

c#调用C++ DLL文件

c#调用C++ DLL文件

6、c#创建控制台应用程序对C++ dll进行访问

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Runtime.InteropServices;

namespace ConsoleApplication1

{

    class Program

    {

        [DllImport("Win32Project1.dll")]

        public static extern int mySum(int x, int y);

        static void Main(string[] args)

        {

            int x = mySum(5, 9);

            x = x++;

            Console.WriteLine(x.ToString());

            string y=  Console.ReadLine();     

        }

    }

}

执行后得出正确结果:14

c#调用C++ DLL文件

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