How to correctly move pointer between managed and umanaged mode in mixed-mode C++?

Started by
0 comments, last by SOS 18 years, 9 months ago
I'm doing some interop and passing a structure to managed code via an IntPtr. I convert the structure to the IntPtr as follows: System::IntPtr func(Event &e) { return __nogc new System::IntPtr(&e); } I'm not too confident about my mixed-mode C++ skills, but I think that's right... right? However, the data I get back from PtrToStructure (with the IntPtr returned from func() as the first parameter, and the type of a managed replica of the Event structure as the second parameter) gives me complete gibberish. It's not a member alignment problem either, because the data is supposed to be mostly nulls but I get numbers in the millions (Event contains mostly pointers to other structures). What am I doing wrong?
Advertisement
Ok, I solved it.

In case anyone wants to know, the problem was caused by IntPtr.
Basically, IntPtr(void*) does NOT wrap a pointer into a managed pointer. Instead, it creates a managed pointer TO an unmanaged pointer. Very wrong.

The solution was to simply use static_cast to convert the umanaged pointer into a managed one.

This topic is closed to new replies.

Advertisement