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

Update SDL2.cs #244

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open

Conversation

DeafMan1983
Copy link

@DeafMan1983 DeafMan1983 commented May 28, 2023

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.

Please do not use Marshall for Net 6.x and greater for NativeAOT.
Sorry I added stackAlloc[bufferSize] = It is wrong

Now I replace with NativeMenory.Alloc() = It is correct for NativeAot.
@karadevnet
Copy link

i can not find example with ttf print font in sdl window. i made all examples and they work cool, but ca not find any example to print ttf font strings in sdl window. can you make a simple like all others to can try it and do not lose 3 month time to wonder hot to do it.

and need to make and more examples to can learn from them how to use this sdl wrapper.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants