I want to read a MemoryMappedFile with a struct. Strings are located in this file. So I created a struct like this:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct MemMappedFile
{
[...]
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 15)]
public string SomeString;
[...]
}
I get the error
System.ArgumentException: The specified Type must be a struct containing no references.
From my understanding the string is a reference type but the marshaling should manage this, but it doesn't - probably I am using it wrong.
How can I use a string in a struct, which needs to be out of value types only?
CodePudding user response:
The string itself is not stored in the struct. Instead a reference to the string is stored in the struct, so the struct size never changes.
string is not a value type; .NET strings are interned, which means that each unique string is stored in a look-up table in memory.
CodePudding user response:
@Heinzi's answer was correct.
I had to use byte[] and use an unsafe context.
