My C# code uses a Managed C++ Wrapper. To make a new object of this Wrapper's type, I need to convert String's to Sbyte*'s. A few StackOverflow.com posts discussed how to convert String to byte[], as well as byte[] to sbyte[],开发者_Python百科 but not String to sbyte*.
msdn.social.com offers advice on how to convert a byte array to a string:
> // 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);
However, "bytes" is not of type sbyte*. My following attempts to convert bytes to sbyte* failed:
1. Convert.ToSbyte(bytes); 2. cast: (sbyte*) bytes;
Please advise me on how to convert a C# string to an sbyte*.
Also, please talk about any side effects from introducing sbyte*, which I believe is unsafe code.
Thanks, Kevin
Hmmm how about something like this:
(didnt test it, dont give me -1 if it doesnt work, I just believe that it should) :))
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
}
}
You can do that way:
sbyte[] sbytes = Array.ConvertAll(bytes, q => Convert.ToSByte(q));
sbyte[] and sbyte* are almost the same thing (almost)
sbyte[] str1; sbyte* str2;
&str1[0] is a pointer to the first element of the array of chars str2 is a pointer to a char, which presumably has a bunch of consecutive chars following it, followed by a null terminator
if you use str1 as an array, you know the length without a null terminator. but if you want to pass str1 to a string api that requires sbyte*, you use &str1[0] to turn it into a sbyte*, and then you stripped away array length information, so you have to make sur eyou're null terminated.
Cipi's answer shows you how to convert an array to a pointer, C# makes it hard to use pointers, on purpose. in C or C++ arrays and pointers are similar.
http://www.lysator.liu.se/c/c-faq/c-2.html
http://pw1.netcom.com/~tjensen/ptr/pointers.htm
精彩评论