SDL2-CS icon indicating copy to clipboard operation
SDL2-CS copied to clipboard

Update SDL2.cs

Open DeafMan1983 opened this issue 1 year ago • 1 comments

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.

DeafMan1983 avatar May 28 '23 12:05 DeafMan1983