Search code examples
.netc++-cliunmanagedmanagedmixed-mode

How can I send a managed object to native function to use it?


How can I send a managed object to native function to use it?

void managed_function()
{
  Object^ obj = gcnew Object();

  void* ptr = obj ??? // How to convert Managed object to void*?

  unmanaged_function(ptr);
}

// The parameter type should be void* and I can not change the type.
// This function is native but it uses managed object. Because type of ptr could not be 
// Object^ I called it "Unmanaged Function".
void unmanaged_function(void* ptr)
{
  Object^ obj = ptr ??? // How to convert void* to Managed object?

  obj->SomeManagedMethods();
}

Solution

  • After googling, reading MSDN and try some codes, I found this method to pass a managed object to an unmanaged function.

    These methods show how to convert Object^ to void* and convert void* to Object^.

    using namespace System;
    using namespace System::Runtime::InteropServices;
    
    void managed_function() 
    { 
      Object^ obj = gcnew Object();
    
      // Convert Object^ to void*
      GCHandle handle = GCHandle::Alloc(obj);
      IntPtr pointer = GCHandle::ToIntPtr(handle);
      void* ptr = pointer.ToPointer();
    
      unmanaged_function(ptr);
    
      handle.Free();
    } 
    
    void unmanaged_function(void* ptr) 
    {
      // Convert void* to Object^
      IntPtr pointer(ptr);
      GCHandle handle = GCHandle::FromIntPtr(pointer);
      Object^ obj = (Object^)handle.Target;
    
      obj->SomeManagedMethods();
    } 
    

    Note: if "unmanaged_function" has variable arguments, this method won't work.