1 #region Copyright notice and license 2 3 // Copyright 2015 gRPC authors. 4 // 5 // Licensed under the Apache License, Version 2.0 (the "License"); 6 // you may not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, software 12 // distributed under the License is distributed on an "AS IS" BASIS, 13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 // See the License for the specific language governing permissions and 15 // limitations under the License. 16 17 #endregion 18 19 using System; 20 using System.Runtime.InteropServices; 21 using System.Text; 22 23 namespace Grpc.Core.Internal 24 { 25 /// <summary> 26 /// Useful methods for native/managed marshalling. 27 /// </summary> 28 internal static class MarshalUtils 29 { 30 static readonly Encoding EncodingUTF8 = System.Text.Encoding.UTF8; 31 static readonly Encoding EncodingASCII = System.Text.Encoding.ASCII; 32 33 /// <summary> 34 /// Converts <c>IntPtr</c> pointing to a UTF-8 encoded byte array to <c>string</c>. 35 /// </summary> PtrToStringUTF8(IntPtr ptr, int len)36 public static string PtrToStringUTF8(IntPtr ptr, int len) 37 { 38 var bytes = new byte[len]; 39 Marshal.Copy(ptr, bytes, 0, len); 40 return EncodingUTF8.GetString(bytes); 41 } 42 43 /// <summary> 44 /// Returns byte array containing UTF-8 encoding of given string. 45 /// </summary> GetBytesUTF8(string str)46 public static byte[] GetBytesUTF8(string str) 47 { 48 return EncodingUTF8.GetBytes(str); 49 } 50 51 /// <summary> 52 /// Get string from a UTF8 encoded byte array. 53 /// </summary> GetStringUTF8(byte[] bytes)54 public static string GetStringUTF8(byte[] bytes) 55 { 56 return EncodingUTF8.GetString(bytes); 57 } 58 59 /// <summary> 60 /// Returns byte array containing ASCII encoding of given string. 61 /// </summary> GetBytesASCII(string str)62 public static byte[] GetBytesASCII(string str) 63 { 64 return EncodingASCII.GetBytes(str); 65 } 66 67 /// <summary> 68 /// Get string from an ASCII encoded byte array. 69 /// </summary> GetStringASCII(byte[] bytes)70 public static string GetStringASCII(byte[] bytes) 71 { 72 return EncodingASCII.GetString(bytes); 73 } 74 } 75 } 76