c# unsafe 代码

164 阅读1分钟

string 转 sbyte*

  1. Marshal 推荐
 string v = string.Empty;
 IntPtr bt = (IntPtr)Marshal.StringToHGlobalAnsi(flag);
 IntPtr intPtrStr = (IntPtr)Marshal.StringToHGlobalAnsi(flag2);
 unsafe
 {
     sbyte* b = (sbyte*)bt;
     sbyte* sbyteFlag = (sbyte*)intPtrStr;    
     ...
     string value = new String(b);
     ...
  
 }
  1. 类c指针
byte[] bytes = Encoding.ASCII.GetBytes(flag);                
unsafe
{
  fixed (byte* p = bytes)
  {
       sbyte* sbyteFlag = (sbyte*)p;
       sbyte sb = new sbyte();
       sbyte* b = &sb;
       ...
       string value = new String(b);
       ...
  }