如何在C#中获取C++ DLL导出的字符串数组及优化实现方案
C#调用C++ DLL返回字符串列表的实现方案
原有代码的核心问题
当前写法完全无法正常运行,存在两个根本匹配错误:
- C侧直接导出返回
std::vector<std::string>的函数,不符合C ABI跨语言调用标准。STL容器是C标准库的内部实现,不同编译环境下的内存布局没有统一规范,C#的P/Invoke机制完全无法识别这类对象的结构,调用必然触发内存崩溃、数据乱码。 - C#端将返回值声明为
StringBuilder,和C++侧返回的vector对象没有任何内存结构上的相似性,根本拿不到有效数据。
可落地的合规实现方案
跨DLL传递字符串列表时,绝对不要直接把STL对象作为函数参数或返回值,必须拆成C#可以识别的原生基础类型传递,下面是两种生产环境常用的实现方式:
方案1:内存由C#侧分配,无跨边界内存管理成本
这种方式的内存完全由C#侧申请、释放,不会出现内存泄漏、跨堆释放的问题,适合数据量不大的场景。
改造后的C++侧代码
#include "stdafx.h" #include <stdlib.h> #include <string.h> // 函数参数: // outBuffer: C#传入的预分配缓冲区,所有字符串以\0作为分隔符连续存储 // outCount: 指向整型的指针,用来回传实际返回的字符串个数 extern "C" __declspec(dllexport) void GetProduct(char* outBuffer, int* outCount) { const char* productList[] = {"Citroen", "C5", "MOP-C5"}; int listLen = sizeof(productList) / sizeof(productList[0]); *outCount = listLen; int offset = 0; for (int i = 0; i < listLen; i++) { strcpy_s(outBuffer + offset, 65536 - offset, productList[i]); offset += (int)strlen(productList[i]) + 1; // 每个字符串自带结束\0,作为下一个字符串的分隔 } outBuffer[offset] = '\0'; // 列表末尾追加\0作为整体结束标记 }
对应的C#侧调用代码
[DllImport("ProductLibrary.dll", CallingConvention = CallingConvention.Cdecl)] public static extern void GetProduct(StringBuilder outBuffer, out int outCount); static void Main(string[] args) { // 预分配足够容量的缓冲区,容量根据业务最大数据量调整 StringBuilder buffer = new StringBuilder(65536); int productCount; GetProduct(buffer, out productCount); // 按\0拆分得到完整的字符串数组 string[] productArray = buffer.ToString() .Split(new[] { '\0' }, StringSplitOptions.RemoveEmptyEntries); // 直接遍历即可 foreach (var product in productArray) { Console.WriteLine(product); } }
方案2:内存由C++侧分配,配套统一释放逻辑
如果无法提前确定字符串总长度,不想让C#预分配超大缓冲区,可以采用C++侧分配内存、配套专属释放函数的方式。注意必须用COM内存分配器(CoTaskMemAlloc)申请内存,避免跨堆释放错误。
改造后的C++侧代码
#include "stdafx.h" #include <objbase.h> #include <string.h> // 返回连续存储的字符串缓冲区指针 extern "C" __declspec(dllexport) char* GetProduct(out int outCount) { const char* productList[] = {"Citroen", "C5", "MOP-C5"}; int listLen = sizeof(productList) / sizeof(productList[0]); *outCount = listLen; // 计算总需要的内存大小 int totalBufferSize = 1; // 留1字节存末尾的结束\0 for (int i = 0; i < listLen; i++) { totalBufferSize += (int)strlen(productList[i]) + 1; } // 用CoTaskMemAlloc申请的内存,C#可以直接通过Marshal释放 char* buffer = (char*)CoTaskMemAlloc(totalBufferSize); int offset = 0; for (int i = 0; i < listLen; i++) { strcpy_s(buffer + offset, totalBufferSize - offset, productList[i]); offset += (int)strlen(productList[i]) + 1; } buffer[offset] = '\0'; return buffer; } // 配套的内存释放函数,做兜底保护 extern "C" __declspec(dllexport) void FreeProductBuffer(char* buffer) { if (buffer != nullptr) { CoTaskMemFree(buffer); } }
对应的C#侧调用代码
[DllImport("ProductLibrary.dll", CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr GetProduct(out int outCount); [DllImport("ProductLibrary.dll", CallingConvention = CallingConvention.Cdecl)] public static extern void FreeProductBuffer(IntPtr buffer); static void Main(string[] args) { int productCount; IntPtr bufferPtr = GetProduct(out productCount); try { List<string> productList = new List<string>(); int offset = 0; for (int i = 0; i < productCount; i++) { // 从指针偏移位置读取ANSI字符串 string item = Marshal.PtrToStringAnsi(bufferPtr + offset); productList.Add(item); offset += item.Length + 1; // 偏移量加上字符串长度和末尾的\0字节 } // 遍历拿到的字符串列表 foreach (var product in productList) { Console.WriteLine(product); } } finally { // 必须释放C++侧申请的内存,防止泄漏 FreeProductBuffer(bufferPtr); } }
为什么不推荐直接传递STL容器
- STL的
vector、string属于C++标准库的内部实现,没有公开的二进制跨接口规范,不同编译器、不同运行时版本下的结构差异极大,C#没有对应的数据结构可以映射,强行走P/Invoke会出现未定义行为。 - 哪怕是纯C++项目跨DLL传STL对象,如果编译时用的运行时版本不一致,都可能出现堆损坏、内存释放失败的问题,跨语言传给C#的可靠性更低。
内容的提问来源于stack exchange,提问作者user6223604
相关产品推荐
相关产品推荐

