Created
March 6, 2019 12:05
-
-
Save mgravell/0914818c0f1db594a5e75c631128fe77 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Runtime.CompilerServices; | |
using System.Text; | |
static class P | |
{ | |
static unsafe void Main() | |
{ | |
var arr = new [] | |
{ | |
new NonBlittableType(42, Encoding.UTF8.GetBytes("hello")), // 42=0x2a, for later comparison | |
new NonBlittableType(12, Encoding.UTF8.GetBytes("world")), // 12=0x0c, for later comparison | |
new NonBlittableType(05, null), // 05=0x05, for later comparison | |
}; | |
Span<NonBlittableType> span = arr; | |
fixed(void* ptr = &Unsafe.As<NonBlittableType, byte>(ref span[0])) | |
{ | |
var bytes = new Span<byte>(ptr, span.Length * Unsafe.SizeOf<NonBlittableType>()); | |
Console.WriteLine($"bytes: {bytes.Length}; span: {span.Length} elements, each size {Unsafe.SizeOf<NonBlittableType>()}"); | |
for (int i = 0; i < bytes.Length; i++) | |
{ | |
Console.Write(bytes[i].ToString("x2")); | |
} | |
Console.WriteLine(); | |
// example outputs: | |
// d8162cc74b0100002a00000000000000a0172cc74b0100000c0000000000000000000000000000500000000000000 | |
// d81602803c0200002a00000000000000a01702803c0200000c0000000000000000000000000000500000000000000 | |
// d8160280860200002a00000000000000a0170280860200000c0000000000000000000000000000500000000000000 | |
// or basically: | |
// ****************XXXXXXXX00000000 for each element, | |
// where **************** is a **reference** as bytes === gibberish, | |
// XXXXXXXX is the integer value of x, CPU-endian, and 00000000 is zero padding | |
} | |
} | |
readonly struct NonBlittableType | |
{ | |
public NonBlittableType(int x, byte[] obj) | |
{ | |
_x = x; | |
_obj = obj; | |
} | |
readonly int _x; | |
readonly byte[] _obj; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment