C++ Usage of AsyncCallback

C++ Usage of AsyncCallback

本文关键字:AsyncCallback of Usage C++      更新时间:2023-10-16

我有一个方法,例如:

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需要复制构造函数、复制赋值和析构函数来正确释放本机对象。