我有一个来自外部库的大类,我需要在托管代码中使用非托管回调。 非托管代码简化:
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
我可能犯了一些概念性错误。 感谢您的帮助。
你不能简单地将函数指针转换为
std::function
指针,你需要构造一个std::function
对象:
auto pc = ProgressCallback(reinterpret_cast<void(*)(const std::string &, Float)>(ptr));
this->gen->SetCallback(pc);