ImGuiNET / ImGui.NET

An ImGui wrapper for .NET.
MIT License
1.91k stars 307 forks source link

NullTerminatedString #163

Open andreakarasho opened 4 years ago

andreakarasho commented 4 years ago

Hi, what is the purpose of the NullTerminatedString struct? Something related to the translation between byte[] and string when using InputText?

mellinoe commented 4 years ago

Yes, it is just a small translation type to make it easier to expose raw byte* strings from the native side. Arguably, it's not very useful, and the code generator could just be modified on this line to do the string marshalling inline, or with a helper function, but that would be hiding the underlying pointer (which might not be a bad thing).

mellinoe commented 4 years ago

Sorry, to clarify, it doesn't have anything to do with InputText per se. It's used to wrap byte* strings that appear in native structures, ImGuiIO.IniFilename and ImGuiIO.LogFilename, for instance.

andreakarasho commented 4 years ago

i started to use it with InputText function and i think it is very useful with some helper methods built around this struct.

I played with it a little bit:

Declaration

~~The ArrayPool<byte>.Shared.Rent(N) stores the byte[] data for us! In this way we avoid to write code 2x.~~

private static NullTerminatedString _nt_string = new NullTerminatedString((byte*) Unsafe.AsPointer(ref ArrayPool<byte>.Shared.Rent(256)[0]));

String to byte*

string str_value = "hi";
 if (!string.IsNullOrEmpty(str_value))
     Unsafe.CopyBlock(ref _nt_string.Data[0], ref Encoding.ASCII.GetBytes(str_value)[0], 256);

byte* to String

string str_value = _nt_string.ToString();
// or simply
string str_value = _nt_string; // .ToString() is called implicitly

EDIT: something wrong with GC :D

andreakarasho commented 4 years ago

About the String -> byte*, i didn't find any suitable solution without calling the GetBytes method. I'm 100% sure it's due to their immutability.

mellinoe commented 4 years ago

I'm not sure what you're trying to do here. Could you clarify?