答案是使用P/Invoke技术调用C++ DLL。首先在C++中用extern "C"和__declspec(dllexport)导出函数,如Add和PrintMessage;然后在C#中用[DllImport]声明对应方法,指定CallingConvention和CharSet;对于结构体需用[StructLayout]定义内存布局;最后确保平台匹配、DLL路径正确及函数名未被修饰。

在C#中调用C++编写的DLL,通常使用P/Invoke(Platform Invoke)技术。它允许托管代码调用非托管DLL中的函数,比如用C或C++编写的Win32 API或自定义DLL。下面详细介绍如何实现这一过程。
首先确保你的C++ DLL正确导出了可供外部调用的函数。推荐使用 extern "C" 防止C++命名修饰,并使用 __declspec(dllexport) 导出函数。
示例C++代码(MyCppDll.cpp):
立即学习“C++免费学习笔记(深入)”;
extern "C" __declspec(dllexport) int Add(int a, int b) {
return a + b;
}
<p>extern "C" __declspec(dllexport) void PrintMessage(const char* msg) {
printf("Message: %s\n", msg);
}
编译为DLL后,例如生成 MyCppDll.dll。
使用 [DllImport] 特性声明要调用的函数。注意指定DLL名称和参数类型映射。
C#代码示例:
using System;
using System.Runtime.InteropServices;
<p>class Program
{
// 声明Add函数
[DllImport("MyCppDll.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int Add(int a, int b);</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">// 声明PrintMessage函数
[DllImport("MyCppDll.dll", CallingConvention = CallingConvention.Cdecl,
CharSet = CharSet.Ansi)]
public static extern void PrintMessage(string msg);
static void Main()
{
int result = Add(5, 3);
Console.WriteLine("5 + 3 = " + result);
PrintMessage("Hello from C#!");
}}
关键点说明:
当需要传递结构体或数组时,必须在C#中定义对应的布局。
例如C++结构体:
struct Point {
int x;
int y;
};
extern "C" __declspec(dllexport) double Distance(Point p1, Point p2);
C#中对应声明:
[StructLayout(LayoutKind.Sequential)]
public struct Point
{
public int x;
public int y;
}
<p>[DllImport("MyCppDll.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern double Distance(Point p1, Point p2);
如果传指针,可使用 ref 或 out 参数,或配合 Marshal 类手动管理内存。
可使用工具如dumpbin /exports MyCppDll.dll查看实际导出函数名。
基本上就这些。只要DLL导出规范,C#通过P/Invoke调用并不复杂,但要注意类型映射和调用约定的一致性。
以上就是C#如何调用C++的DLL C# P/Invoke平台调用非托管代码的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号