A read-only MemoryManager class. #106606
Replies: 1 comment 1 reply
-
Note that MemoryManager does add rather unpleasant overhead that may not be suitable for something as performance-critical as a string primitive. After extensively evaluating all alternatives, I had to settle on Memory-like layout of byte[] + offset + length in U8String: https://github.com/U8String/U8String/blob/main/Sources/U8String/U8String.cs#L83-L84 It makes it easy to create Once you have this building block, it becomes a non-issue to provide convenient API for pinning, marshalling, etc. Much like |
Beta Was this translation helpful? Give feedback.
-
When I created the
CString
class in my libraryRxmxnx.PInvoke.Extensions
to facilitate the handling of UTF-8 text in native calls, it was implemented through three different types of memory, which could be behind any instance:ReadOnlySpan<Byte>
resulting from the execution of a delegate.3.The memory is unmanaged and accessed through a pointer.
For the case of unmanaged memory, it wouldn't make sense to create an instance of
ReadOnlyMemory<Byte>
.For the case of memory managed through a
ReadOnlySpan<Byte>
resulting from the execution of a delegate it might make sense in some scenarios with certain restrictions, but that is not the focus of this discussion.However, for buffer managed memory, it should be entirely possible, but I couldn't achieve a satisfactory implementation, mainly due to two scenarios:
CString
instances must be immutable.CString
instance can be based on eitherByte[]
orString
buffers.When a
CString
instance is based on a byte array, each UTF-8 unit is stored in a position of the array that serves as the buffer.When a
CString
instance is based on a string, each pair of UTF-8 units is stored in a position of the UTF-16 string.For the buffer based on
Byte[]
, it is simple to obtain aReadOnlyMemory<Byte>
instance since I can derive it from the.AsMemory()
extension, although this instance would give me write access to the buffer, which is not desired as it is supposed to be immutable.For the buffer based on String, it is possible to create a
ReadOnlyMemory<Char>
instance from the String buffer, but this doesn't help to create one of typeReadOnlyMemory<Byte>
.I considered finding a way to create memory using the
MemoryManager<T>
class; However, this approach is designed for managing mutable memory, so implementing it would pose a risk to the integrity of any CString instance.Beta Was this translation helpful? Give feedback.
All reactions