我继承了一个 C++ DLL 及其相关头文件,其函数声明如下
int func1(int i);
int func2(char* s);
我还继承了一个引用VC++引用类,它包装了上面的DLL以便在C#环境中使用
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* 参数传递给函数 func2_w?
最佳答案
正如我在评论中所说,这可能是我见过的最愚蠢的包装器。您必须手动分配 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);
}
关于c# - 如何将 C# 类似字符串的变量传递给 sbyte* 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51207422/