gpt4 book ai didi

c# - 从托管 .NET 代码调用 native 回调(使用 COM 加载托管代码时)

转载 作者:太空狗 更新时间:2023-10-29 20:08:53 26 4
gpt4 key购买 nike

关于 native /托管互操作的大量错误信息让我感到非常困惑。

我有一个常规的 C++ exe,它不是使用 CLR 东西构建的(它既不是托管 C++ 也不是 C++/CLI,而且永远不会)。这个 C++ exe 是“负责的”,没有它的托管包装器。

我想从我的 C++ exe 访问我在 C# 程序集中的一些代码。我可以使用 COM 从我的 C++ 代码访问 C# 程序集。但是,当我的 C# 代码检测到一个事件时,我希望它回调到我的 C++ 代码中。将在运行时提供回调的 C++ 函数指针。请注意,C++ 函数指针指向在 exe 的执行环境中找到的函数。它可以从那里使用静态成员。我不希望托管代码尝试加载一些 DLL 来调用函数(没有 DLL)。

如何通过 COM/.NET 将此 C++ 函数指针传递到我的 C# 代码,并让我的 C# 代码成功调用它?

谢谢!

最佳答案

您可能想要使用 Marshal.GetDelegateForFunctionPointer :

  1. 创建一个与 native 函数签名相匹配的委托(delegate)类型,牢记编码类型的正确方法并使用 MarshalAs根据需要
  2. 尽你所能将 native 函数指针从你的 native 代码传递给你的 C# 代码(在你的情况下,看起来你可以使用你的 COM -> C# 连接)
  3. 使用 Marshal.GetDelegateForFunctionPointer 将指针转换为 C# 可调用委托(delegate)
  4. 使用您的参数调用委托(delegate)

张俊峰有一个这样做的例子here .

注意 MSDN 上提到的限制:

The GetDelegateForFunctionPointermethod has the following restrictions:

  • Generics are not supported in interopscenarios.
  • You cannot pass an invalid functionpointer to this method.
  • You can use this method only for pureunmanaged function pointers.
  • You cannot use this method withfunction pointers obtained through C++or from the GetFunctionPointer method.
  • You cannot use this method to create adelegate from a function pointer toanother managed delegate.

关于 C++ 的部分可能是指类方法的函数指针。这应该仍然适用于全局函数。

关于c# - 从托管 .NET 代码调用 native 回调(使用 COM 加载托管代码时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2925450/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com