C#调用C++dll方法步骤

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C#调用C++dll方法步骤

  2021-04-03 我要评论

C#调用C++dll的方法和步骤

其他分享涉及到的概念和方法对于像我这样比较菜的选手看起来比较费劲并且很难抓住重点,这里我总结了一段时间的研究成果供初学者救济之用,简单明了。

1、新建项目->Visual C++->Win32项目 MyDLL

注意:C++编写的dll一般是不能直接拿来C#调用,需要先新建个C++的工程把dll里的方法重新封装成可被C#外部调用的函数。

2、MyDLL.cpp里的代码如下:

extern "C" _declspec(dllexport)int add(int a ,int b) 

{ 

int sum=a+b;

return sum;

}

注意:函数前一定要加extern "C"  _declspec(dllexport),可被外部引用

3、项目->属性->常规->公共语言运行库支持->公共语言运行库支持(/clr)

4、F5编译程序,在Debug文件夹中找到生成MyDLL.dll目标文件备用

1、方法/步骤2

新建项目->Visual C#->控制台应用程序 dllConsoleApplication1

2、将步骤1生成的MyDLL.dll文件copy到dllConsoleApplication1工程的根目录下

3、

Program.cs代码如下using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Runtime.InteropServices;  //必须添加,不然DllImport报错namespace dllConsoleApplication1{  class CPPDLL  {    [DllImport("MyDLL.dll", CharSet = CharSet.Ansi)] //引入dll,并设置字符集    public static extern inProgram.cs代码如下using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Runtime.InteropServices;  //必须添加,不然DllImport报错namespace dllConsoleApplication1{  class CPPDLL  {    [DllImport("MyDLL.dll", CharSet = CharSet.Ansi)] //引入dll,并设置字符集    public static extern int add(int a ,int b);  }  class Program  {    static void Main(string[] args)    {     

t add(int a ,int b);  }  class Program  {    static void Main(string[] args)    {      int sum=CPPDLL.add(3, 4);    }  }}

 int sum=CPPDLL.add(3, 4);    }  }}

4、

编译程序,在程序中加断点,查看函数的计算结果

5、到这里,C++dll里的方法已经在C#里调用成功了。到这里,C++dll里的方法已经在C#里调用成功了。

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们