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

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

相关推荐
清辞85343 分钟前
C++入门(底层知识C与C++的不同)
开发语言·c++·算法
fqbqrr1 小时前
2510C++,api设计原则,不除零
开发语言·c++
玩泥巴的1 小时前
.NET驾驭Word之力:基于规则自动生成及排版Word文档
c#·word·.net·com互操作
fqbqrr1 小时前
2510d,C++虚混杂
c++·d
科比不来it1 小时前
Go语言数据竞争Data Race 问题怎么检测?怎么解决?
开发语言·c++·golang
SunnyDays10112 小时前
C# 实现高保真 Excel 转 PDF(无需 Office 环境)
经验分享·c#·excel转pdf
给大佬递杯卡布奇诺2 小时前
FFmpeg 基本API av_seek_frame函数内部调用流程分析
c++·ffmpeg·音视频
uxiang_blog2 小时前
C++进阶:重载类型转换
linux·开发语言·c++
攻城狮CSU2 小时前
C# 数据加载专题 之泛型序列化
java·servlet·c#
爱编程的鱼2 小时前
C# 参数详解:从基础传参到高级应用
开发语言·microsoft·c#