Jump to content
  • Advertisement
Sign in to follow this  
Numsgil

[.net] void* userData and Object^

This topic is 3894 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm trying to write a C++/CLR wrapper around a C++ library so that I can call it from C#. I don't want to modify the C++ library at all. The C++ library has several structures with a void* userData field. What I'd like to do is take an Object^ to a managed class, round trip it through the void* userData, and retrieve back the Object^ when I need it. The unmanaged code is never going to interact with the void* userData, other than storing it and retrieving it. .NET pitches a fit when I try this, and with good reason I'm sure. Is there a way to force it to convert the Object^ to a void* and back again anyway?

Share this post


Link to post
Share on other sites
Advertisement
If all you want to do is store the pointer and make it accessible in a .net-friendly way, why not just throw it in an IntPtr and expose that through a property?

Share this post


Link to post
Share on other sites
Quote:
Original post by gharen2
If all you want to do is store the pointer and make it accessible in a .net-friendly way, why not just throw it in an IntPtr and expose that through a property?


That only works for the reverse: if I had an unmanaged ptr that I wanted to use in a managed class.

GCHandle looks like the answer, I'll try to play around with it and see what I get.

Share this post


Link to post
Share on other sites
This is what I have so far. It seems to work in any simple test I try.

I don't understand enough about the garbage collector to know for sure, but my gut tells me I'm doing this wrong, and this'll cause a memory leak. I'd be grateful for anyone illuminating me either way.


property Object^ UserData
{
Object^ get()
{
return System::Runtime::InteropServices::GCHandle::FromIntPtr((System::IntPtr)def->userData).Target;
}

void set(Object^ value)
{
GCHandle^ gch = GCHandle::Alloc(value);
def->userData = (void *)gch->ToIntPtr(*gch);
}
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!