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

前端 未结 2 1402
抹茶落季
抹茶落季 2020-12-16 06:55

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 conv         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-16 07:10

    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.

提交回复
热议问题