c#程序调用c++开发dll库

最近算法组同事开发一个接口,如获取名称:

cpp 复制代码
extern "C" __declspec(dllexport) void GetName(std::string& name);

打包成 dll 库后,供我这边 c# 项目中调用如下:

cs 复制代码
[DllImport("Test.dll", EntryPoint = "GetName", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)]
public static extern void GetName(out StringBuilder name);

// 获取名称
public static string GetName()
{
    StringBuilder name = new StringBuilder(256);
    GetName(out name);

    return name.ToString();
}

正常情况下,并没有什么问题。但是如果连续两次调用 dll 库中方法,程序必报错,提示尝试读取或写入受保护的内存

开始觉得是因为传参被修改导致,沟通后将名称通过函数返回值返回,避免参数修改。

cpp 复制代码
extern "C" __declspec(dllexport) std::string GetName();

对应的,项目中程序也调整为:

cs 复制代码
[DllImport("Test.dll", EntryPoint = "GetName", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)]
public static extern string GetName();

// 获取名称
public static string GetName()
{
    string name = GetName();

    return name;
}

运行后程序直接报错了,一番查询后大概率是因为 c# 中的 string 类型和 c++ 中的 std::string 类别不匹配导致。同时让同事改为返回 const char* 试试。即:

cpp 复制代码
extern "C" __declspec(dllexport) const char* GetName();

调用如下:

cs 复制代码
[DllImport("Test.dll", EntryPoint = "GetName", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr GetName();

public static string GetName()
{
    IntPtr ptr = GetName();
    string name = Marshal.PtrToStringAnsi(ptr);

    return name;
}

至此,问题才得以解决。在正确返回信息的同时,即使连续调用也依然稳定可行。

相关推荐
..过云雨6 分钟前
17-2.【Linux系统编程】线程同步详解 - 条件变量的理解及应用
linux·c++·人工智能·后端
搬砖的工人23 分钟前
写了一个IIS监控工具,对付“假死“后自动重启站点
c#
量子炒饭大师27 分钟前
Cyber骇客的逻辑节点美学 ——【初阶数据结构与算法】二叉树
c语言·数据结构·c++·链表·排序算法
fpcc1 小时前
C++编程实践—false_type和true_type的实践应用
c++
量子炒饭大师1 小时前
Cyber骇客神经塔尖协议 ——【初阶数据结构与算法】堆
c语言·数据结构·c++·二叉树·github·
王老师青少年编程2 小时前
2025年12月GESP(C++二级): 环保能量球
c++·算法·gesp·csp·信奥赛·二级·环保能量球
CoderCodingNo2 小时前
【GESP】C++五级真题(贪心思想考点) luogu-P11960 [GESP202503 五级] 平均分配
开发语言·c++·算法
不会写代码的里奇3 小时前
深入解析ASR技术:从原理到C++高性能实现
c++
CSDN_RTKLIB3 小时前
【类定义系列六】C++17新特性
开发语言·c++
hd51cc4 小时前
MFC文件操作
c++·mfc