SDL2-CS
SDL2-CS copied to clipboard
Update SDL2.cs
Please do not use Marshall for Net 6.x and greater for NativeAOT.
Replace with NativeMemory.Alloc();
I tested and it works fine like charm:
namespace Test;
using System.Runtime.InteropServices;
using System.Text;
unsafe class Program
{
static unsafe string UTF8_ToManaged(byte *s, bool freePtr = false)
{
if (s == null)
{
return string.Empty;
}
byte* ptr = (byte*) s;
while (*ptr != 0)
{
ptr++;
}
string result = System.Text.Encoding.UTF8.GetString(
s, (int) (ptr - (byte*) s)
);
if (freePtr)
{
NativeMemory.Free(s);
}
return result;
}
static int Utf8Size(string str)
{
if (str == null)
{
return 0;
}
return (str.Length * 4) + 1;
}
static unsafe byte* Utf8EncodeHeap(string str)
{
if (str == null)
{
return (byte*) 0;
}
int bufferSize = Utf8Size(str);
byte *buffer = (byte *)NativeMemory.Alloc((nuint)bufferSize);
fixed (char* strPtr = str)
{
Encoding.UTF8.GetBytes(strPtr, str.Length + 1, buffer, bufferSize);
}
return buffer;
}
static void Main(string[] args)
{
string from_str = "Hello World!";
byte *from_to_bytePointer = Utf8EncodeHeap(from_str);
string result = UTF8_ToManaged(from_to_bytePointer);
Console.WriteLine(result);
}
}
Can you test it? I have success. I hope you replace my improvement.