Request: Make us able to get pointer to data for NativeString64

As title says, make us able to get the pointer to data of NativeString64 to be used in unsafe context. E.g. sending data through networks have to be done something like this for now, which unnecessarily copies to temporary buffer:

    NativeString64 username = new NativeString64("HelloWorld");
    var dataWriter = new DataStreamWriter((NativeString64.MaxLength * sizeof(char) + sizeof(byte)), Allocator.Temp);
    NativeArray<char> tempData = new NativeArray<char>(NativeString64.MaxLength, Allocator.Temp);
    int outLen = 0;
    int len = 0;
    len = username.Length;
    dataWriter.Write((byte)len);
    username.CopyTo((char*)Unity.Collections.LowLevel.Unsafe.NativeArrayUnsafeUtility.GetUnsafePtr<char>(tempData), out outLen, len);
    dataWriter.WriteBytes((byte*)Unity.Collections.LowLevel.Unsafe.NativeArrayUnsafeUtility.GetUnsafePtr<char>(tempData), len * 2);
    connection.connection.Send(driver, dataWriter);
    tempData.Dispose();

Simply moving the order of the NativeStrings would fix this.

public struct NativeString64 : IComparable<NativeString64>, IEquatable<NativeString64>
{
    public const int MaxLength = (64 - sizeof(int)) / sizeof(char);
    public int Length;
    private unsafe fixed uint buffer[MaxLength/2];
...
}

to

public struct NativeString64 : IComparable<NativeString64>, IEquatable<NativeString64>
{
    private unsafe fixed uint buffer[MaxLength/2];
    public const int MaxLength = (64 - sizeof(int)) / sizeof(char);
    public int Length;
 
...
}

then we can simply write

NativeString64 username = new NativeString64("HelloWorld");
var dataWriter = new DataStreamWriter((NativeString64.MaxLength * sizeof(char) + sizeof(byte)), Allocator.Temp);
fixed(NativeString64* stringPtr = &connectData.username)
{
    dataWriter.Write((byte)stringPtr->Length);
    dataWriter.WriteBytes((byte*)stringPtr, stringPtr->Length*2);
}
connection.connection.Send(driver, dataWriter);
1 Like

Can’t you just offset the pointer by 4 instead of having to rearrange it?