C# .NET - C#语言基础 - C#语法
C#.NET调用C++函数的实现
C#要调用C++写的函数,怎么实现呢?

本例子的C++函数为非托管代码,使用g++编译。在Windows上测试通过。

1、使用Visual Stuido 2022创建一个 控制台应用 ,框架选择.NET 7

2、准备C++函数,使用文本文件编辑C++代码文件htadd.cpp :
int HtAdd(int a,int b)
{
return a + b;// by 何问起
}

3、编译C++函数代码文件,在Windows 上已经安装了MinGw,打开命令提示符,编译C++代码:
g++ htadd.cpp -std=c++17 -shared -o htadd.dll

编译后会输出htadd.dll 文件。
参考:何问起C++教程
备注,使用的编译器版本信息如下图:


如果使用的是i686的编译器(如下图),则应该在x86的解决方案平台下使用。

如果在x64解决方案平台则会报错:
System.BadImageFormatException
HResult=0x8007000B
Message=试图加载格式不正确的程序。 (0x8007000B)
Visual Studio 2022解决方案平台选择如下图:

可进入配置管理器编辑和新建

另外,如果是以下的编译器,在x64平台也报错,应该选择x86平台:

4、编辑第一步创建的控制台应用,C#代码如下:
//  C# 调用C++ 函数  by  何问起 hovertree.com

using System.Runtime.InteropServices;

[DllImport("E:\\HoverTreeTop\\dll\\htadd.dll")]
static extern int HtAdd(int a, int b);

Console.WriteLine("Hello, Hovertree!");

Console.WriteLine(HtAdd(2 , 3).ToString());
按F5开始调试,出现报错如下:
System.EntryPointNotFoundException
HResult=0x80131523
Message=Unable to find an entry point named 'HtAdd' in DLL 'E:\HoverTreeTop\dll\htadd.dll'.
Source=HtConsoleApp
StackTrace:
在 Program.<
$>g__HtAdd|0_0(Int32 a, Int32 b)
...

按 Shift+F5 停止调试

5、修改htadd.cpp文件代码为:
extern "C"  __declspec(dllexport) int HtAdd(int a,int b)
{
return a + b;// by 何问起
}
并重新编译:
g++ htadd.cpp -std=c++17 -shared -o htadd.dll

6、来到VS2022 ,按F5,开始C#项目,成功输出,如下图:


7、总结,可以在C++函数前增加代码:
extern "C" __declspec(dllexport)
使函数可以被C#调用

在Windows上测试通过。

8、也可以在.NET Standard 2.0的类库项目中使用c++函数,以下代码仅限用于Windows系统上,其他系统暂未测试通过,代码如下:
using System.Runtime.InteropServices;

namespace HtCalculator
{
public class HovertreeCalculator
{
[DllImport("E:\\HoverTreeTop\\dll\\htadd.dll")]
static extern int HtAdd(int a, int b);
public static int HtSum(int a, int b)
{
return HtAdd(a,b);
}
}
}

.NET 7 的Console代码如下:
using HtCalculator;

Console.WriteLine("Hello, Hovertree!");

Console.WriteLine(HovertreeCalculator.HtSum(2 , 3).ToString());
运行效果同上。
解决方案结构如下图:


收藏 列表

评论:

导航