using System.Runtime.InteropServices.Marshalling;
using System.Text;
namespace Brutal.SdlApi;
///
/// Marshaller for UTF-8 strings, used by the generated P/Invoke surface for SDL's const char *
/// parameters and returns.
///
[CustomMarshaller(typeof(string), MarshalMode.ManagedToUnmanagedIn, typeof(ManagedToUnmanagedIn))] // string parameter
[CustomMarshaller(typeof(string), MarshalMode.ManagedToUnmanagedOut, typeof(ManagedToUnmanagedOut))] // return string
public static unsafe class CustomStringMarshaller
{
///
/// Custom marshaller to marshal a managed string as a UTF-8 unmanaged string.
///
public ref struct ManagedToUnmanagedIn
{
///
/// Gets the requested buffer size for optimized marshalling.
///
public static int BufferSize => 0x100;
private byte* _unmanagedValue;
private bool _allocated;
///
/// Initializes the marshaller with a managed string and requested buffer.
///
/// The managed string with which to initialize the marshaller.
/// The request buffer whose size is at least .
public void FromManaged(string? managed, Span buffer)
{
_allocated = false;
if (managed is null)
{
_unmanagedValue = null;
return;
}
const int MaxUtf8BytesPerChar = 3;
// >= for null terminator
// Use the cast to long to avoid the checked operation
if ((long)MaxUtf8BytesPerChar * managed.Length >= buffer.Length)
{
// Calculate accurate byte count when the provided stack-allocated buffer is not sufficient
int exactByteCount = checked(Encoding.UTF8.GetByteCount(managed) + 1); // + 1 for null terminator
if (exactByteCount > buffer.Length)
{
buffer = new Span((byte*)NativeMemory.Alloc((nuint)exactByteCount), exactByteCount);
_allocated = true;
}
}
// Unsafe.AsPointer is safe since buffer must be pinned
_unmanagedValue = (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(buffer));
int byteCount = Encoding.UTF8.GetBytes(managed, buffer);
buffer[byteCount] = 0; // null-terminate
}
///
/// Converts the current managed string to an unmanaged string.
///
/// An unmanaged string.
public byte* ToUnmanaged() => _unmanagedValue;
///
/// Frees any allocated unmanaged memory.
///
public void Free()
{
if (_allocated)
NativeMemory.Free(_unmanagedValue);
}
}
///
/// Converts an unmanaged UTF-8 string returned by SDL back to a managed string.
///
public static class ManagedToUnmanagedOut
{
///
/// Converts an unmanaged UTF-8 string to a managed string, preserving a NULL pointer as
/// .
///
/// The unmanaged UTF-8 string, or NULL.
/// The managed string, or if is NULL.
public static string? ConvertToManaged(byte* unmanaged)
{
if (unmanaged == null)
return null;
return Marshal.PtrToStringUTF8((IntPtr)unmanaged);
}
}
}