答案:通过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++函数供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) #endifextern "C" MYLIB_API int Add(int a, int b); extern "C" MYLIB_API void GetString(char* buffer, int bufferSize);
// mylib.cpp
立即学习“C++免费学习笔记(深入)”;
include "mylib.h"
include
int Add(int a, int b) { return a + b; }
void GetString(char buffer, int bufferSize) { const char str = "Hello from C++!"; strncpy_s(buffer, bufferSize, str, strlen(str)); }
编译为DLL后,函数名在导出表中保持原始名称,便于P/Invoke查找。
C#中声明并调用非托管函数
C#使用[DllImport]特性声明外部DLL函数。需指定DLL名称和调用约定(通常为CallingConvention.Cdecl或StdCall)。
示例C#代码:
using System; using System.Runtime.InteropServices;class Program { [DllImport("mylib.dll", CallingConvention = CallingConvention.Cdecl)] public static extern int Add(int a, int b);
[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; }[DllImport("mylib.dll", CallingConvention = CallingConvention.Cdecl)] public static extern void SetPoint(ref Point p);
使用ref传递结构体引用,保证按地址传参。注意不要在托管代码中直接释放非托管内存,避免双释放问题。
常见问题与最佳实践
P/Invoke调用容易出错,以下是一些实用建议:
- 确保DLL位于运行路径下(如exe同目录),否则会抛出DllNotFoundException
- 调用约定必须匹配,C++若用__cdecl,C#也要设为CallingConvention.Cdecl
- 字符串编码需统一,Unicode环境下建议使用CharSet.Unicode并修改C++接口
- 调试时可用Dependency Walker或dumpbin /exports检查DLL导出函数名
- 考虑使用x86/x64平台目标一致,避免位数不匹配导致崩溃
对于频繁调用或复杂交互,可考虑使用C++/CLI作为桥梁,实现更自然的托管与非托管混合编程。
基本上就这些。只要注意函数导出、调用约定和数据类型映射,P/Invoke就能稳定工作。










