C++ Usage of AsyncCallback
C++ Usage of AsyncCallback
我有一个方法,例如:
void Something::DoSomething(double d1, double d2, void* callback)
{
AsyncCallback^ acb = gcnew AsyncCallback(this, System::IntPtr(callback)); //error C3364: 'System::AsyncCallback' : invalid argument for delegate constructor; delegate target needs to be a pointer to a member function
sensor->BeginSearch(d1, d2, acb);
}
我怎样才能让它工作?
此方法 shell 将导出,并将由本机 c++ 应用使用。
编辑:
经过一些搜索,我目前的进展如下:
.h
typedef std::tr1::function<void(void)>* callback_function;
ref class Something
{
public:
void DoSomething(double d1, double d2, callback_function callback);
void DoSomethingCallback (IAsyncResult^ ar);
private:
callback_function m_callback;
}
。.cpp
void Something::DoSomething(double d1, double d2, callback_function callback)
{
m_callback = callback;
AsyncCallback^ acb = gcnew AsyncCallback(this, &Something::DoSomethingCallback);
sensor->BeginSearch(d1, d2, acb);
}
void Something::DoSomethingCallback(IAsyncResult^ ar)
{
(*m_callback());
}
本机代码中的用法:
h.
class NativeClass
{
public:
void NativeFunction(double d1, double d2);
std::tr1::function<void()> m_callback;
}
。.cpp
void NativeClass::NativeFunction(double d1, double d2)
{
m_callback = std::tr1::bind(&SomethingElse::DoSomethingCallback, this);
sensor->DoSomething(d1, d2, &m_callback);
}
void SomethingElse::DoSomethingCallback(void)
{
// Does something
}
现在它似乎有效。我现在面临的唯一问题是,当程序在名为xxfunction
的类中停止(*m_callback())
,我的托管代码会引发以下异常 somwhere:
An unhandled exception of type System.AccessViolationException occurred in .dll Additional information: An attempt was made to read or write in the protected memory. This is an indication that other memory is corrupted.
&SomethingElse::DoSomethingCallback
是成员函数的地址。
typedef void (*callback_function)(void);
是指向非成员函数的指针。
两者不兼容。
您可能想要std::function<void(void)>
,但不能将其直接放在托管类型中,因此最终会得到
typedef std::function<void(void)>* callback_function;
这将被称为
(*m_callback)(); // works for pointer to std::function, and also the most correct syntax for a plain function pointer
然后,您的ref class Something
需要复制构造函数、复制赋值和析构函数来正确释放本机对象。
相关文章:
- Usages of std::move
- 使用 [] 运算符时"binding reference of type discards qualifiers"
- 如何处理 c++ 中类实现中的"invalid use of non-static data member"?
- 具有变量Number of Arguments的std::函数的矢量
- Capacity of a deque
- Deprecation of _writeBarrier()
- constexpr begin of a std::array
- 如何调整 std::vector of Eigen::MatrixXd 的大小
- C++ "error: invalid use of void expression"
- 我看到"use of undeclared identifier"错误,有人可以告诉我如何解决它吗?
- 赛通"Cannot take address of memoryview slice"
- C++ Version Of Double.longBitsToDouble
- 收到错误"invalid use of non-static data member 'stu::n' "
- C++ Usage of AsyncCallback
- 错误:"Left of getValue must have class/struct/union"
- Centos7 g++ "to_string is not in a member of std"
- 在C++中使用 Catch 测试框架编译错误"error: expected ';' at end of declaration list"
- 传递 std::vector of std::shared_ptr,而不是更新对象
- C++/SDL "initial value of reference to a non-const must be an lvalue"
- Declaration of IntRect SFML