答案:通过P/Invoke实现C#调用C++ DLL需使用extern "C"和__declspec(dllexport)导出函数,避免名称修饰;C#中用[DllImport]声明,指定正确的调用约定和字符集;传递字符串时使用StringBuilder,结构体需用[StructLayout]匹配内存布局;注意DLL路径、平台一致性及内存管理,避免双释放。

在Windows平台上,C++与C#之间的互操作是一个常见需求,尤其是在需要调用本地C++代码来提升性能或复用已有库时。P/Invoke(Platform Invoke)是.NET提供的一种机制,允许托管代码(如C#)调用非托管DLL中的函数。下面介绍如何通过P/Invoke实现C#调用C++编写的原生函数,并给出关键技巧和注意事项。
要让C#通过P/Invoke调用C++函数,必须将C++函数导出为C风格的接口,避免C++的名称修饰(name mangling)。使用extern "C"和__declspec(dllexport)确保函数能被正确导出。
示例C++ DLL代码(mylib.cpp):
// mylib.h
#ifdef MYLIB_EXPORTS
#define MYLIB_API __declspec(dllexport)
#else
#define MYLIB_API __declspec(dllimport)
#endif
<p>extern "C" MYLIB_API int Add(int a, int b);
extern "C" MYLIB_API void GetString(char* buffer, int bufferSize);</p><p>// mylib.cpp</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/6e7abc4abb9f" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">C++免费学习笔记(深入)</a>”;</p><h1>include "mylib.h"</h1><h1>include <string.h></h1><p>int Add(int a, int b) {
return a + b;
}</p><p>void GetString(char<em> buffer, int bufferSize) {
const char</em> str = "Hello from C++!";
strncpy_s(buffer, bufferSize, str, strlen(str));
}
编译为DLL后,函数名在导出表中保持原始名称,便于P/Invoke查找。
C#使用[DllImport]特性声明外部DLL函数。需指定DLL名称和调用约定(通常为CallingConvention.Cdecl或StdCall)。
示例C#代码:
using System;
using System.Runtime.InteropServices;
<p>class Program {
[DllImport("mylib.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;">[DllImport("mylib.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern void GetString(StringBuilder buffer, int bufferSize);
static void Main() {
// 调用Add
int result = Add(3, 5);
Console.WriteLine($"Add result: {result}");
// 调用GetString
var sb = new StringBuilder(256);
GetString(sb, sb.Capacity);
Console.WriteLine($"String from C++: {sb.ToString()}");
}}
注意:字符串传递时使用StringBuilder作为可变缓冲区,CharSet设为Ansi以匹配C风格字符串。
当涉及结构体、指针或数组时,需在C#端定义对应的布局,并使用[StructLayout]确保内存对齐一致。
例如,C++结构体:
struct Point {
int x;
int y;
};
extern "C" MYLIB_API void SetPoint(Point* p);
C#对应声明:
[StructLayout(LayoutKind.Sequential)]
public struct Point {
public int x;
public int y;
}
<p>[DllImport("mylib.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void SetPoint(ref Point p);
使用ref传递结构体引用,保证按地址传参。注意不要在托管代码中直接释放非托管内存,避免双释放问题。
P/Invoke调用容易出错,以下是一些实用建议:
对于频繁调用或复杂交互,可考虑使用C++/CLI作为桥梁,实现更自然的托管与非托管混合编程。
基本上就这些。只要注意函数导出、调用约定和数据类型映射,P/Invoke就能稳定工作。
以上就是C++如何与C#进行互操作(P/Invoke)_C++与C#互操作技巧与P/Invoke使用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号