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;
}

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

相关推荐
阿正的梦工坊17 分钟前
【Rust】08-集合类型、字符串与迭代器入门
开发语言·rust·c#
FuckPatience23 分钟前
C# 使用泛型协变将派生类类型替换为基类类型
开发语言·c#
guygg8830 分钟前
C# 生成中间带 Logo 头像的二维码
开发语言·c#
小欣加油1 小时前
leetcode1926 迷宫中离入口最近的出口
数据结构·c++·算法·leetcode·职场和发展
Java面试题总结1 小时前
C#12 中的 Using Alias
开发语言·windows·c#
加号31 小时前
【C#】 ASCII 码转字符串技术解析
开发语言·c#
星恒随风2 小时前
C++ 类和对象入门(五):初始化列表、explicit 和 static 成员详解
开发语言·c++·笔记·学习·状态模式
浪客灿心2 小时前
项目篇:模块设计与实现
数据库·c++
2601_961875242 小时前
高考真题word版下载|2025高考全科真题可编辑文档
c#·word·ar·vr·mr·高考·oneflow
牛油果子哥q3 小时前
【C++ STL vector】C++ STL vector 终极精讲:动态数组底层原理、两倍扩容机制、迭代器失效、增删查改、性能剖析与工程避坑指南
开发语言·c++