See the question and my original answer on StackOverflow

The error you get is HostApiBufferTooSmall because you pass a buffer of invalid size. Your size argument is a pointer to an array that contains garbage. You can fix it like this:

var ptr = stackalloc ushort[ushort.MaxValue];
var size = stackalloc nuint[1];
*size = ushort.MaxValue;
var hr = get_hostfxr_path(ptr, size, null);

Or simply this:

var ptr = stackalloc ushort[ushort.MaxValue];
var size = (nuint)ushort.MaxValue;
var hr = get_hostfxr_path(ptr, &size, null);

Also, you can use ushort, but it may be easier to use .NET's natural char and string types directly, this should work too:

const int bufferSize = 2048; // or ushort.MaxValue but seems too large
var str = new string('\0', bufferSize);
var size = bufferSize / sizeof(char);
fixed (char* buffer = str)
{
    var hr = get_hostfxr_path((ushort*)buffer, (nuint*)&size, null);
    if (hr >= 0)
    {
        str = str[..(size - 1)]; // final string
    }
}