首页 > 解决方案 > 将“this”传递给 C API 回调,获取 void* 用户数据

问题描述

我正在用 C++/CLI 包装器包装 C API,以便从 C# 项目中使用它。C API 的callback其中一项功能需要 a。回调签名采用void*用户数据参数。

我想this作为void*用户数据参数传递给 C API,但我没有成功(编译失败)。此外,传递“this”并不像this引用托管类那么容易,所以我当然必须在传递它之前先固定引用。

我也不确定如何将void*参数转换回ManagedClass^回调函数中的 a 。

代码:

public ref class ManagedClass
{
public:
    static void __stdcall CallbackFunc( int, void* userData )
    {
          // How can I cast the void* parameter back to
          // ManagedClass^ ??
    }

    void Open(  )
    {     
         // I know I need to pin the reference to myself
         // but I'm unsure how to go about it. How can I store
         // this in a pin_ptr??       
         ptr = this;

         // Open the third party C-API passing in
         // my callback function and a reference to
         // myself.
         thirdPartyApiOpen( &CallbackFunc, ptr );
    }   
 private:
    pin_ptr<ManagedClass^> ptr; 
};

标签: c++c++-cli

解决方案


推荐阅读