Is there a way to marshal a structure (possibly stored in a TypedReference) to unmanaged memory without actually boxing it? The type of the structure isn't known at runtime, so I can't use the generic overload of StructureToPtr (.NET 4.5.1). I can get a MethodInfo of the StructureToPtr overload, but there doesn't seem to be a way to invoke it passing a generic reference or a TypedReference.
Edit: The generic StructureToPtr still boxes the structure, so trying to invoke it is useless.
I've finally found the answer, the
SafeBuffer
class. It contains exactly what I wanted - structure with marshalling methods using bothTypedReference
and generic parameters. So, it's really simple then to make a wrapper:Usage
Now, does it actually have any advantages over the non-generic object-taking methods in the
Marshal
class? It seems theStructureToPtr
takes about 80 % less time, andPtrToStructure
can take almost 95 % less time. Also, these methods can handle nullable types correctly.