我的 C# 代码使用托管 C++ 包装器。要创建此 Wrapper 类型的新对象,我需要将 String 转换为 Sbyte*。 StackOverflow.com 的一些帖子讨论了如何将 String 转换为 byte[],以及如何将 byte[] 转换为 sbyte[],但没有讨论将 String 转换为 sbyte*。
msdn.social.com 提供了有关如何将字节数组转换为字符串的建议:
> // convert String to Sbyte*
> string str = "The quick brown, fox jumped over the gentleman.";
>
> System.Text.ASCIIEncoding encoding = new
> System.Text.ASCIIEncoding();
>
> Byte[] bytes = encoding.GetBytes(str);
但是,“bytes”不是 sbyte* 类型。我以下将字节转换为 sbyte* 的尝试失败了:
1. Convert.ToSbyte(bytes); 2. cast: (sbyte*) bytes;
请告诉我如何将 C# 字符串转换为 sbyte*。
此外,请谈谈引入 sbyte* 的任何副作用,我认为这是不安全的代码。
谢谢, 凯文
最佳答案
嗯嗯,这样的事情怎么样:
(没有测试它,如果它不起作用,请不要给我 -1,我只是相信它应该):))
string str = "The quick brown fox jumped over the gentleman.";
byte[] bytes = Encoding.ASCII.GetBytes(str);
unsafe
{
fixed (byte* p = bytes)
{
sbyte* sp = (sbyte*)p;
//SP is now what you want
}
}
关于C#:将字符串转换为 Sbyte*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5666073/