Calling a C# function from unmanaged c++ (via a managed wrapper)

左心房为你撑大大i 提交于 2019-12-12 12:32:27

问题


I have C++ source & headers for a set of libraries which I need to call from a C# application. I've created a managed C++ wrapper around the functions I need and am able to call them from C# marshalling the data backwards and forwards.

Now the hard part..

My unmanaged C++ library generates status messages as it runs and I'd like to be able to display these from the calling C# application. My current thinking goes like this:

I'd like the unmanaged C++ library code to call a function in my C# code that I pass to the managed wrapper as I create it. I've found a few tutorials on Code Project but the syntax seem to be out of date.

If anyone has some sample code or could point me in the direction of a good tutorial that would be great.

Thanks in advance for any help.


回答1:


You can pass a .NET delegate to a C++/CLI function that takes a pointer to a function with "matching" arguments.

Caveats

  1. The pointer-to-function must be STDCALL calling conventions
  2. If the delegate is a member of an object, this pointer to function will not count as a reference to keep the object alive. You have to maintain a reference to the object during the time that the callback is held

Since you think your examples are out of date, I am going to assume you are using the new syntax of C++/CLI. Here is a CodeProject with an example of how to do that

http://www.codeproject.com/KB/mcpp/FuncPtrDelegate.aspx



来源:https://stackoverflow.com/questions/5780368/calling-a-c-sharp-function-from-unmanaged-c-via-a-managed-wrapper

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