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

8 篇文章 0 订阅
文章讲述了开发团队在C#项目中调用C++DLL库时遇到的问题,涉及到类型不匹配和参数传递方式对内存保护的影响,最终通过返回constchar*并使用Marshal.PtrToStringAnsi进行转换解决了问题。
摘要由CSDN通过智能技术生成

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

extern "C" __declspec(dllexport) void GetName(std::string& name);

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

[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 库中方法,程序必报错,提示尝试读取或写入受保护的内存

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

extern "C" __declspec(dllexport) std::string GetName();

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

[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* 试试。即:

extern "C" __declspec(dllexport) const char* GetName();

        调用如下:

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

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值