I have this code which doesn't compile:
public struct MyStruct
{
private fixed uint myUints[32];
public uint[] MyUints
{
get
{
return this.myUints;
}
set
{
this.myUints = value;
}
}
}
Now, I know why the code won't compile, but I'm apparently at the point where I'm too tired to think, and need some help to put me in the right direction. I haven't worked with unsafe code in a while, but I'm pretty sure I need to do an Array.Copy
(or Buffer.BlockCopy
?) and return a copy of the array, however those don't take the arguments I need. What am I forgetting about?
Thanks.
You have to work in a fixed
context when working with a fixed
buffer:
public unsafe struct MyStruct {
private fixed uint myUints[32];
public uint[] MyUints {
get {
uint[] array = new uint[32];
fixed (uint* p = myUints) {
for (int i = 0; i < 32; i++) {
array[i] = p[i];
}
}
return array;
}
set {
fixed (uint* p = myUints) {
for (int i = 0; i < 32; i++) {
p[i] = value[i];
}
}
}
}
}
There may be an easier solution, but this works:
public unsafe struct MyStruct
{
private fixed uint myUints[32];
public uint[] MyUints
{
get
{
fixed (uint* ptr = myUints)
{
uint[] result = new uint[32];
for (int i = 0; i < result.Length; i++)
result[i] = ptr[i];
return result;
}
}
set
{
// TODO: make sure value's length is 32
fixed (uint* ptr = myUints)
{
for (int i = 0; i < value.Length; i++)
ptr[i] = value[i];
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With