简体   繁体   English

从非托管c ++调用C#函数(通过托管包装器)

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

I have C++ source & headers for a set of libraries which I need to call from a C# application. 我有一组库的C ++源代码和标题,我需要从C#应用程序调用它们。 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. 我已经创建了一个围绕我需要的函数的托管C ++包装器,并且能够从C#调用它们来向前和向前编组数据。

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. 我的非托管C ++库在运行时生成状态消息,我希望能够从调用C#应用程序中显示这些消息。 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. 我希望非托管C ++库代码在我的C#代码中调用一个函数,我在创建它时将其传递给托管包装器。 I've found a few tutorials on Code Project but the syntax seem to be out of date. 我在Code Project上找到了一些教程,但语法似乎已经过时了。

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. 在此先感谢您的帮助。

You can pass a .NET delegate to a C++/CLI function that takes a pointer to a function with "matching" arguments. 您可以将.NET委托传递给C ++ / CLI函数,该函数将指向具有“匹配”参数的函数的指针。

Caveats 注意事项

  1. The pointer-to-function must be STDCALL calling conventions 指向函数的指针必须是STDCALL调用约定
  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. 由于您认为您的示例已过时,我将假设您使用的是C ++ / CLI的新语法。 Here is a CodeProject with an example of how to do that 这是一个CodeProject,其中包含如何执行此操作的示例

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM