【问题标题】:How can I pass a C# String-like variable to a sbyte* parameter?如何将 C# 类字符串变量传递给 sbyte* 参数?
【发布时间】:2018-07-06 09:38:39
【问题描述】:

我继承了一个带有相关头文件的 C++ DLL,函数声明如下

int func1(int i);
int func2(char* s);

我还继承了一个引用 VC++ 引用类,它包装了上面要在 C# 环境中使用的 DLL

public ref class MyWrapperClass
{
    int func1_w(int i)
    {
        return func1(i);
    }
    int func2_w(char* s)
    {
        return func2(s);
    }
}

在我的 C# 应用程序中,我可以使用 func1_w(int i),但我不明白如何将字符串传递给 func2_w(sbyte* s):我收到一个错误,提示我无法获得指向sbyte。我将 C# 项目设置为不安全并将函数声明为不安全。

如何将 sbyte* 参数传递给 functiuon func2_w?

【问题讨论】:

  • 那个 ref 类非常糟糕,应该将包装器声明为 int func2_w(System::String^ s) 以便可以从任何托管语言轻松调用它。谷歌“convert from system::string to char*”找到你需要的字符串转换代码。

标签: c# c++ string cross-language sbyte


【解决方案1】:

正如我在评论中所说,这可能是我见过的最愚蠢的包装。您必须手动分配 ansi 字符串。两种方式:

string str = "Hello world";

IntPtr ptr = IntPtr.Zero;

try
{
    ptr = Marshal.StringToHGlobalAnsi(str);

    // Pass the string, like:
    mwc.func2_w((sbyte*)ptr);
}
finally
{
    Marshal.FreeHGlobal(ptr);
}

另一种方式,使用Encoding.Default(但请注意终止\0的特殊处理)

string str = "Hello world";

// Space for terminating \0
byte[] bytes = new byte[Encoding.Default.GetByteCount(str) + 1];
Encoding.Default.GetBytes(str, 0, str.Length, bytes, 0);

fixed (byte* b = bytes)
{
    sbyte* b2 = (sbyte*)b;
    // Pass the string, like:
    mwc.func2_w(b2);
}

【讨论】:

    【解决方案2】:

    最后我使用了以下方法:

    sbyte[] buffer = new sbyte[256];
    String errorMessage;
    fixed (sbyte* pbuffer = &buffer[0])
    {
        megsv86bt_nips.getLastErrorText(pbuffer);
        errorMessage = new string(pbuffer);
    };
    

    有人在我的问题的 cmets 中发布了它,但我再也看不到它了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-03
      相关资源
      最近更新 更多