1 // 2 // Safe wrapper for a string and its UTF8 encoding 3 // 4 // Authors: 5 // Aleksey Kliger <aleksey@xamarin.com> 6 // Rodrigo Kumpera <kumpera@xamarin.com> 7 // 8 // Copyright 2016 Dot net foundation. 9 // Licensed under the MIT license. See LICENSE file in the project root for full license information. 10 // 11 12 using System; 13 using System.Runtime.CompilerServices; 14 15 namespace Mono { 16 internal struct SafeStringMarshal : IDisposable { 17 readonly string str; 18 IntPtr marshaled_string; 19 20 [MethodImplAttribute(MethodImplOptions.InternalCall)] StringToUtf8Mono.SafeStringMarshal21 public extern static IntPtr StringToUtf8 (string str); 22 23 [MethodImplAttribute(MethodImplOptions.InternalCall)] GFreeMono.SafeStringMarshal24 public extern static void GFree (IntPtr ptr); 25 SafeStringMarshalMono.SafeStringMarshal26 public SafeStringMarshal (string str) { 27 this.str = str; 28 this.marshaled_string = IntPtr.Zero; 29 } 30 31 public IntPtr Value { 32 get { 33 if (marshaled_string == IntPtr.Zero && str != null) 34 marshaled_string = StringToUtf8 (str); 35 return marshaled_string; 36 } 37 } 38 DisposeMono.SafeStringMarshal39 public void Dispose () { 40 if (marshaled_string != IntPtr.Zero) { 41 GFree (marshaled_string); 42 marshaled_string = IntPtr.Zero; 43 } 44 } 45 } 46 } 47