C#: Converting String to Sbyte*

Kevin Meredith picture Kevin Meredith · Apr 14, 2011 · Viewed 17k times · Source

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[], 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

Answer

Cipi picture Cipi · Apr 14, 2011

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
    }               
}