From e7c1d05fa64fde86ec9f5cca038eb9459a70f9f6 Mon Sep 17 00:00:00 2001 From: Susko3 Date: Mon, 15 Apr 2024 20:27:41 +0200 Subject: [PATCH] Add helper for making null-terminated byte arrays --- SDL3-CS.Tests/Program.cs | 13 +++++++++++++ SDL3-CS/SDL3.cs | 14 ++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/SDL3-CS.Tests/Program.cs b/SDL3-CS.Tests/Program.cs index 6e87f94..609d1fe 100644 --- a/SDL3-CS.Tests/Program.cs +++ b/SDL3-CS.Tests/Program.cs @@ -14,6 +14,19 @@ namespace SDL3.Tests { Console.OutputEncoding = Encoding.UTF8; + unsafe + { + // Encoding.UTF8.GetBytes can churn out null pointers and doesn't guarantee null termination + fixed (byte* badPointer = Encoding.UTF8.GetBytes("")) + Debug.Assert(badPointer == null); + + fixed (byte* pointer = UTF8GetBytes("")) + { + Debug.Assert(pointer != null); + Debug.Assert(pointer[0] == '\0'); + } + } + SDL_SetHint(SDL_HINT_WINDOWS_CLOSE_ON_ALT_F4, "null byte \0 in string"u8); Debug.Assert(SDL_GetHint(SDL_HINT_WINDOWS_CLOSE_ON_ALT_F4) == "null byte "); diff --git a/SDL3-CS/SDL3.cs b/SDL3-CS/SDL3.cs index 5b46e55..bf00f9f 100644 --- a/SDL3-CS/SDL3.cs +++ b/SDL3-CS/SDL3.cs @@ -2,7 +2,9 @@ // See the LICENCE file in the repository root for full licence text. using System; +using System.Diagnostics; using System.Runtime.InteropServices; +using System.Text; namespace SDL { @@ -25,5 +27,17 @@ namespace SDL return s; } + + /// + /// UTF8 encodes a managed string to a byte array suitable for use in ReadOnlySpan<byte> parameters of SDL functions. + /// + /// The string to encode. + /// A null-terminated byte array. + public static byte[] UTF8GetBytes(string s) + { + byte[] array = Encoding.UTF8.GetBytes(s + '\0'); + Debug.Assert(array[^1] == '\0'); + return array; + } } }