2 // Safe wrapper for a string and its UTF8 encoding
5 // Aleksey Kliger <aleksey@xamarin.com>
6 // Rodrigo Kumpera <kumpera@xamarin.com>
8 // Copyright 2016 Dot net foundation.
9 // Licensed under the MIT license. See LICENSE file in the project root for full license information.
13 using System.Runtime.CompilerServices;
16 internal struct SafeStringMarshal : IDisposable {
18 IntPtr marshaled_string;
20 [MethodImplAttribute(MethodImplOptions.InternalCall)]
21 public extern static IntPtr StringToUtf8 (string str);
23 [MethodImplAttribute(MethodImplOptions.InternalCall)]
24 public extern static void GFree (IntPtr ptr);
26 public SafeStringMarshal (string str) {
28 this.marshaled_string = IntPtr.Zero;
33 if (marshaled_string == IntPtr.Zero && str != null)
34 marshaled_string = StringToUtf8 (str);
35 return marshaled_string;
39 public void Dispose () {
40 if (marshaled_string != IntPtr.Zero) {
41 GFree (marshaled_string);
42 marshaled_string = IntPtr.Zero;