0

目前我正在使用两层。一层是 C++/CLI,另一层是我没有源代码的非托管 C++ 图形库。当用户在非托管代码中移动操纵器时,我将数据传递给非托管代码并在回调函数“intermediateCallback”中接收数据。

下面是我如何定义名为“tempFunc”的委托类型。它什么也不接受,也不返回。'intermediateCallback' 的 'void* userData' 参数是我想要转回委托实例的参数。此参数作为转换为 IntPtr 强制转换为 void* 的委托传递到未管理的代码中。我可以将 void* 变回 IntPtr,但如何将其变回委托类型“tempFunc”?

delegate void tempFunc();

//the function that the delegate instance actually points to
void libCoin3D::CenterballDragger::memberCallback()
{
....
}

//the function that the unmanaged code will call and pass data to
void intermediateCallback( void * userData, SoDragger *dragger)
{
    System::IntPtr ptr=(System::IntPtr)userData;
    tempFunc^ tF=(tempFunc^)ptr;//this line does not work, I want to do something like it
}

最初,当我将委托传递给非托管代码时,这就是我将委托变成 void* 的方式。

如果 tF 是由以下定义的委托:

tempFunc^ tF=gcnew tempFunc(this,&libCoin3D::CenterballDragger::memberCallback);

我将其转换为:

(System::Void*)(System::Runtime::InteropServices::Marshal::GetFunctionPointerForDelegate(tF))

那么是否可以将 void* 转换为 tempFunc?

4

1 回答 1

3

我解决了一个类似的问题:

delegate void tempFunc();

//the function that the delegate instance actually points to
void libCoin3D::CenterballDragger::memberCallback()
{
  ....
}

//the function that the unmanaged code will call and pass data to
void __stdcall intermediateCallback( void * userData, SoDragger *dragger)
{
  using System::Runtime::InteropServices::GCHandle;
  GCHandle gch = GCHandle::FromIntPtr((System::IntPtr)userData);
  tempFunc^ tF = (tempFunc^)gch.Target;

  tF();

  gch.Free(); // If the call only once, otherwise it is necessary to keep the pointer and delete it later     

}

tempFunc^ tF = gcnew tempFunc(this, &libCoin3D::CenterballDragger::memberCallback);

 // pass to unmanaged code
setCallback( &intermediateCallback, (void*)GCHandle::ToIntPtr(GCHandle::Alloc(tF)) );
于 2012-11-02T07:16:41.663 回答