marshaling an unmanaged struct

L

Lee Crabtree

I have several unmanaged struct types that I've created equivalent managed
struct types for. How do I marshal the managed structs into their unmanaged
versions and vice versa?

Here's a quick example of what I'm working with:

unmanaged C++:

typedef struct _UStruct
{
UCHAR length;
USHORT type;
}UStruct;

and the managed version:

[StructLayout(LayoutKind::Sequential, Pack=1)]
__value public struct _M_UStruct
{
unsigned char length;
unsigned short type;
};

Lee
 
L

Lee Crabtree

Alright, after some work, I've found something that, at the very least,
compiles. Can anyone tell me if this is going to work?

_M_UStruct manStruct = some init value;
System::Object* obj = __box(manStruct);

IntPtr pnt = Marshal::AllocHGlobal(Marshal::SizeOf(obj));

Marshal::StructureToPtr(obj, pnt, true);

functionCall(static_cast<UStruct*>(const_cast<void*>(static_cast<const
void*>(pnt))));

Marshal::FreeHGlobal(pnt);

God, that is so gross looking.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top