/// <summary> /// Initialize instance with .NET string <see cref="s"/> /// </summary> /// <param name="s">.NET string to wrap into a UTF8 sequence of unmanaged bytes.</param> public Utf8String(string s) { Contract.Requires(s != null, "s is not null"); // This code is not optimized. One could actually read the string and copy the content // directly in _handle without hitting any allocation. This would require us to include // the logic of converting .NET strings into UTF8 ourselves, something we do not want // to do for the time being. For now we only avoid the allocation of an extra byte array // for small strings (see the implementation of GetUtf8Bytes). int nb; byte[] bytes = GetUtf8Bytes(s, out nb); IntPtr lPtr = SDL.SDL_malloc((IntPtr)(nb + 1)); if (lPtr == IntPtr.Zero) { throw new OutOfMemoryException("Cannot Allocate Utf8String"); } else { Marshal.Copy(bytes, 0, lPtr, nb); ((byte *)lPtr)[nb] = 0; } _count = nb; _capacity = nb + 1; _handle = lPtr; Contract.Ensures((_handle != IntPtr.Zero), "handle set"); Contract.Ensures((_capacity >= s.Length + 1), "capacity_greater_than_input"); Contract.Ensures(ReferenceEquals(s, String()) || (String().Equals(s)), "string_set"); }
public IntPtr MarshalManagedToNative(object ManagedObj) { if (ManagedObj == null) { return(IntPtr.Zero); } var str = ManagedObj as string; if (str == null) { throw new ArgumentException("ManagedObj must be a string.", "ManagedObj"); } var bytes = Encoding.UTF8.GetBytes(str); var mem = SDL.SDL_malloc((IntPtr)bytes.Length + 1); Marshal.Copy(bytes, 0, mem, bytes.Length); ((byte *)mem)[bytes.Length] = 0; return(mem); }