C++/CLI 从 typedef std::function 到托管委托

问题描述 投票:0回答:1

我有一个来自外部库的大类,我需要在托管代码中使用非托管回调。 非托管代码简化:

typedef std::function<void(const std::string &, Float)> ProgressCallback;
class MeshGenerator{
public:   
ProgressCallback progress;
/// <summary>
/// set callback
/// </summary>
/// <param name="_callback"></param>
inline void SetCallback(ProgressCallback _callback){ this-> progress =_callback; }   
};

现在我的管理代码简化了:

public delegate void CallbackDelegate(String^ cap, float data);
public ref class MeshWrapper
{

private:
MeshGenerator *gen;
public:
[MarshalAsAttribute(UnmanagedType::FunctionPtr)]
CallbackDelegate^ _Delegate;
inline MeshWrapper(){ 
  this->gen = new MeshGenerator();
  _Delegate = gcnew CallbackDelegate(this, &MeshWrapper::Progress);
  auto ptr = Marshal::GetFunctionPointerForDelegate(_Delegate).ToPointer();
  ProgressCallback *p = static_cast<ProgressCallback*>(ptr);
  this->gen->SetCallback(*p);
}   
inline void Progress(String^ cap, float s){ System::Console::WriteLine(cap + s);}
};

此代码编译,但在 MeshWrapper 构造函数中静态转换(“static_cast(ptr);”)给了我一个空委托。

我可能犯了一些概念性错误。 感谢您的帮助。

c# delegates c++-cli clr
1个回答
0
投票

你不能简单地将函数指针转换为

std::function
指针,你需要构造一个
std::function
对象:

auto pc = ProgressCallback(reinterpret_cast<void(*)(const std::string &, Float)>(ptr));
this->gen->SetCallback(pc);
© www.soinside.com 2019 - 2024. All rights reserved.