I have a struct:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public unsafe struct FieldIndex {
public fixed byte Meta[16];
}
The first byte is TypeCode
. The remaining 15 bytes is a UTF8-encoded string.
I'm using the following to fill the nameBuf
byte array:
private static string GetMetaName (FieldIndex meta) {
var idx = 0;
var bytesOut = 1;
var nameBuf = new byte[Indexer.MAXFIELDNAMELENGTH]; // 15
while (bytesOut < Indexer.MAXFIELDLENGTH) { // 16
nameBuf[idx] = *(byte*)((byte*)&meta + bytesOut);
++bytesOut;
++idx;
}
//var src = (byte*)&field.meta + 1;
//fixed (byte* b = nameBuf) {
// *((byte*)b) = (byte)src;
//}
return BinaryConverter.ToString(nameBuf, 0, Indexer.MAXFIELDNAMELENGTH, Indexer.DefaultEncoding);
}
In the commented code above, I was trying to accomplish the same task without the while
iteration but it does not work (no compile error, just the wrong interpolation). Can I assign nameBuf
without the while
-loop?
Update
I'd also prefer using the (byte*)
rather than Marshal.Copy
.