C ++使用AsyncCallback

时间:2018-10-16 10:34:35

标签: c++ c++-cli

我有一个方法,例如:

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);
}

如何使它正常工作?

将导出此方法外壳,并将由本机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
}

现在看来可行。我现在面临的唯一问题是,我的托管代码在(*m_callback())处的程序中在xxfunction类中抛出了以下异常:

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.

1 个答案:

答案 0 :(得分:0)

&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需要复制构造函数,复制分配和析构函数,以正确释放本机对象。