首页 > 解决方案 > 如何将 C# 类字符串变量传递给 sbyte* 参数?

问题描述

我继承了一个带有相关头文件的 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?

标签: c#c++stringcross-languagesbyte

解决方案


正如我在评论中所说,可能是我见过的最愚蠢的包装。您必须手动分配 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(但请注意对 terminating 的特殊处理\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);
}

推荐阅读