ImGui.NET icon indicating copy to clipboard operation
ImGui.NET copied to clipboard

NullTerminatedString

Open andreakarasho opened this issue 4 years ago • 5 comments

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

andreakarasho avatar Apr 14 '20 19:04 andreakarasho

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 avatar Apr 15 '20 06:04 mellinoe

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.

mellinoe avatar Apr 15 '20 06:04 mellinoe

~~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 avatar Apr 15 '20 09:04 andreakarasho

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.

andreakarasho avatar Apr 15 '20 09:04 andreakarasho

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

mellinoe avatar Apr 16 '20 08:04 mellinoe