Sign in to follow this  

[.net] void* userData and Object^

This topic is 3587 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
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

This topic is 3587 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this