Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get string from ReadOnlyMemory<char> without allocation?

Can we get string reference from ReadonlyMemory<char> without re-allocating on heap.

ReadonlyMemory<char> someChars;//I got ReadOnlyMemory<char> from somewhere
string str = someChars.SomeMethodToGetStringWithoutAllocation();//I am looking for this
like image 845
Arjun Vachhani Avatar asked Sep 19 '25 04:09

Arjun Vachhani


1 Answers

You should be able to reference the same memory using the TryGetString method of the MemoryMarshal class (as noted in the comments).

However, looking at the implementation it seems like this will only work if the memory was originally obtained from a string instance otherwise this method will fail (the internal method GetObjectStartLength will return false).

ReadOnlyMemory<char> s = "foo".AsMemory();
var ok = System.Runtime.InteropServices.MemoryMarshal.TryGetString(s, out string s2, out int start2, out int length2);
Console.WriteLine(ok);      // True
Console.WriteLine(s2);      // foo
Console.WriteLine(start2);  // 0
Console.WriteLine(length2); // 3

ReadOnlyMemory<char> s3 = "foo".ToCharArray();
var ok2 = System.Runtime.InteropServices.MemoryMarshal.TryGetString(s3, out string s4, out int start4, out int length4);
Console.WriteLine(ok2);     // False
Console.WriteLine(s4);      // null
Console.WriteLine(start4);  // 0
Console.WriteLine(length4); // 0

Note: the string reference is the original string reference. TryGetString it is like an unwrap of a ReadOnlyMemory<char>.

like image 120
John Leidegren Avatar answered Sep 21 '25 20:09

John Leidegren