Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add helper for making null-terminated byte arrays #35

Merged
merged 1 commit into from
Apr 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions SDL3-CS.Tests/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,19 @@ public static void Main()
{
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 ");

Expand Down
14 changes: 14 additions & 0 deletions SDL3-CS/SDL3.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand All @@ -25,5 +27,17 @@ public static unsafe partial class SDL3

return s;
}

/// <summary>
/// UTF8 encodes a managed <c>string</c> to a <c>byte</c> array suitable for use in <c>ReadOnlySpan&lt;byte&gt;</c> parameters of SDL functions.
/// </summary>
/// <param name="s">The <c>string</c> to encode.</param>
/// <returns>A null-terminated byte array.</returns>
public static byte[] UTF8GetBytes(string s)
{
byte[] array = Encoding.UTF8.GetBytes(s + '\0');
Debug.Assert(array[^1] == '\0');
return array;
}
}
}