I have the luxury to lightheartedly declare "Folks, I don't know what I was smoking when I said that D structs cannot be implemented as value types in .net", without being afraid of losing any points in any poll.
Further research proved that my initial argument, in .net value types do not participate in garbage collection was... er irrelevant. That's because Walter Bright' s D compiler front-end is smart enough to insert calls to the structs' destructors wherever necessary! Now that's what I call a bright design. It doesn't matter that the CLR does not garbage-collect new-ed value types, because the front-end generates the code that deletes them.
I was running some compiler back-end tests for the D language post-blit operator when I realized that copying value types in IL is straight-forward; you LOAD the source variable / field / argument and STORE into the destination (boom!) whereas bit-copying managed classes is not as trivial.
I did not give up right away. Hanging on to my structs-as-classes implementation, I wrote a run-time helper blitting routine:
using System.Runtime.InteropServices;
// assumes src and dest are of the same type
static public void blit(Object dest, Object src)
{
int size = Marshal.SizeOf(src.GetType());
IntPtr p = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(src, p, false);
Marshal.PtrToStructure(p, dest);
}
finally
{
Marshal.FreeHGlobal(p);
}
}
It did not take long for the truth to dawn upon me: Wow, bit-blitting non-value types is a major pain in the (oh) bum (ah). Efficient that code ain't (or should I say ISN'T? man do those consonants hurt). Honestly, I am not even sure that code is kosher. Better not to get into a pickle if one can avoid it... so back to the struct-as-value type implementation I am.
No comments:
Post a Comment