.net - unmanaged struct to managed marshaling -


i marshal ums s (which of aligned types):

void f(managedstruct ^s) {   ummanagedstruct ums;   fillthestruct(&ums);   s = ? } 

do need allocate unmanaged memory using allochglobal so?:

void f(managedstruct ^s) {   intptr ptr = marshal::allochglobal(marshal::sizeof(s);    fillthestruct(static_cast<unmanagedstruct*>(ptr.topointer);   s = (managedstruct^)marshal::ptrtostruct(ptr, managedstruct::typeid); } 

   void f(managedstruct ^s) 

that's wrong if intended pass value caller. argument must passed reference caller's variable can updated. ^ hat wrong if "managedstruct" in fact value type. use on reference types, kind declare ref struct or ref class. sadly c++/cli doesn't generate diagnostic such usage, assumes intentionally meant box value.

fix:

  void f(managedstruct% s) 

or saner 1 value types:

  managedstruct f() {       unmanagedstruct ums;       fillthestruct(&ums);       return (managedstruct)marshal::ptrtostructure(intptr(&ums), managedstruct::typeid);   } 

with note marshal::ptrtostructure() convenient neither safer nor faster alternative, copying structure members 1 one.


Comments