c# - 如何将 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?
解决方案
正如我在评论中所说,可能是我见过的最愚蠢的包装。您必须手动分配 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);
}
推荐阅读
- reactjs - 使用 framer-motion 和 NextJS (typescript) 共享元素路由转换
- python-3.x - 未找到带有参数“(”,)“的“动作”的反向
- algorithm - Dijkstra 给出了哪条路径?
- vuetify.js - 如何从单个文件组件中的范围样式覆盖 Vuetify 文本字段下划线?
- python - 使用 Python 从多个网页中提取日期
- azure-active-directory - 调用同步 API 时的 InternalServerError
- java - 如何创建一个存在于 Java 方法中的类的对象?
- java - 访问 TextView 的 setText 方法时出现 NullPointerException
- sql - SQL Server 无法理解 xml 中的查找和替换值
- java - Lombok 无法与 IntelliJ 2020.3 社区版一起使用