string csharpString = "Hello, world!"; IntPtr ptr = System.Runtime.InteropServices.Marshal.StringToHGlobalUTF8(csharpString); NSString nsString = NSString.StringWithUTF8String(ptr); System.Runtime.InteropServices.Marshal.FreeHGlobal(ptr);
string csharpString = "こんにちは、世界!"; byte[] utf8Bytes = System.Text.Encoding.UTF8.GetBytes(csharpString); IntPtr ptr = System.Runtime.InteropServices.Marshal.AllocHGlobal(utf8Bytes.Length); System.Runtime.InteropServices.Marshal.Copy(utf8Bytes, 0, ptr, utf8Bytes.Length); NSString nsString = NSString.StringWithUTF8String(ptr); System.Runtime.InteropServices.Marshal.FreeHGlobal(ptr);In this example, we have a C# string object that contains Japanese text. We first convert the string to a byte array using the System.Text.Encoding.UTF8.GetBytes method. We then allocate unmanaged memory using the System.Runtime.InteropServices.Marshal.AllocHGlobal method and copy the byte array to the allocated memory using the System.Runtime.InteropServices.Marshal.Copy method. We create a new NSString object using the StringWithUTF8String method and pass it the pointer to the unmanaged memory. Finally, we free the allocated memory using the System.Runtime.InteropServices.Marshal.FreeHGlobal method. The package library for this class is the MonoTouch framework for iOS development.