Function pointer as a parameter of COM method

笑着哭i 提交于 2019-12-24 19:08:42

问题


I have created COM server in C++ that is used from C# application. Now I have to add one more method to my COM object and one of its parameter must be function pointer to callback function. C++ original function looks like this:

typedef int (__stdcall *tCallBackFunc)(int Param);

void MyFunc(void* CallBackFunc)
{
  int Param;
  //some code
  ((tCallBackFunc)(CallBackFunc))(Param); //call callback function
}

I need to add MyFunc as COM object method. VS VC++ "Add Method" dialog offers some predefined types for COM method parameter like "int*" or "bstr", I tried to define "CallBackFunc" parameter as "int*" type, but I was not able to make it work in C#:

public delegate int  tCallBackFunc(int Param);
...
tCallBackFunc cb; //I will initialize it when it is compiled
MyCOMObject.MyFunc(cb); //cannot find any way to cast cb to "ref int"

It seems I use wrong approach, is there a fast way to declare function pointer as parameter of COM object method in C++ and then use it in C#?


回答1:


The COM way is to make the parameter an interface pointer, and have the interface declare the callback function.




回答2:


+1 for Frederik's answer.

@Michael: It will prove a lot easier than your imagined solution. Especially with

  • object lifetimes
  • process boundaries
  • thread safety (apartment boundaries, IOW)
  • standards conformance (casting function pointers quickly enters the domain of Undefined Behaviour). Why should you worry? Standards conformance must concern you in case a compiler update introduces another optimization that makes your old (non-conformant) code break


来源:https://stackoverflow.com/questions/7875502/function-pointer-as-a-parameter-of-com-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!