【问题标题】:How to use string as parameter in c# functions imported from c++ DLL? [duplicate]如何在从 c++ DLL 导入的 c# 函数中使用字符串作为参数? [复制]
【发布时间】:2020-04-08 15:10:46
【问题描述】:

我有一个用 c++ 编写的 dll。该函数将字符串作为输入,并根据一些内部算法返回一个长整数。该函数在 c++ 中运行时完全按预期工作,但当 dll 与 c# 一起使用时,虽然它没有抛出异常或没有给出错误,但程序停止工作。有人可以帮我吗?

C++

static __declspec(dllexport) long long WriteUserData(string userId, int userIdLen)
 {
    cout<<"ID is: "<<userId<<endl;//In c++ displays output but not when called in c#
    cout<<userIdKen<<endl;
    .
    .SomeCode
    .
    return (some long value)
 }

C#

using System;
    using System.Text;
    using System.Collections.Generic;
    using System.Runtime.InteropServices;

    namespace Extreme.Numerics.QuickStart.CSharp
    {

        class Program
        {
        [DllImport(".dll path..",EntryPoint = @"?...entryPoint....",CallingConvention = CallingConvention.Cdecl)]
        public static extern long WriteUserData(string id, int idLen)

    static void Main(string[] args)
     {
        long Serial= WriteUserData("@@rpan@@@@@@@",13);
        Console.WriteLine("test test test");
     }
    }
}

C# 输出:

Id is:

它不再显示任何内容。最后一行Console.WriteLine("test test test");也没有显示

【问题讨论】:

  • 您是否尝试过使用调试器介入?您还需要在托管(System.String 或 sth.)和非托管(std::string)数据类型之间进行转换
  • 我猜它将 C# 字符串编组为 C 字符串,而不是 C++ std::string

标签: c# c++ dllimport dllexport


【解决方案1】:

在 C++ 方面,从 string 更改为 const char*。把 C# 放在一边。这就是 P/Invoke 在声明端看到 C# string 时的默认期望。

【讨论】:

  • 谢谢+1。我想在 C# 端添加一点,我们需要在要插入字符串的地方使用 StringBuilder
猜你喜欢
  • 1970-01-01
  • 2013-12-21
  • 2011-09-04
  • 2010-11-16
  • 1970-01-01
  • 1970-01-01
  • 2021-10-08
  • 1970-01-01
  • 2018-03-14
相关资源
最近更新 更多