如何将 C# 类似字符串的变量传递给 sbyte* 参数?

Dan*_*rdi 2 c# c++ string cross-language sbyte

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

int func1(int i);
int func2(char* s);
Run Code Online (Sandbox Code Playgroud)

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

public ref class MyWrapperClass
{
    int func1_w(int i)
    {
        return func1(i);
    }
    int func2_w(char* s)
    {
        return func2(s);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

xan*_*tos 5

正如我在评论中所说,这可能是我见过的最愚蠢的包装器。您必须手动分配 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);
}
Run Code Online (Sandbox Code Playgroud)

另一种方式,使用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);
}
Run Code Online (Sandbox Code Playgroud)