本文介绍了将非托管方法作为回调传递给托管C ++ / CLI类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将C ++成员函数作为回调传递给C#项目。我在C ++ / CLI中还有其他项目,我想通过它完成。

I want to pass as callback a C++ member function to a C# project. I have other project in C++/CLI and I want to do it through it.

因此,在我的C ++ / CLI项目的非托管C ++中,我有一个函数对象: std :: function< void(int)>回调;

So, in unmanaged C++ of my C++/CLI project I have a function object:std::function<void(int)>callback;

此函数来自我的C ++项目,它工作正常,我将其保存在那里作为示例以避免上一步。现在,我想将此回调函数传递给我的C#项目。为此,我在非托管C ++中创建了一个方法,将其传递给托管C ++,从这一点开始,最终将其传递给C#。我想要这样的东西:

This function is coming from my C++ project and it works fine, I save it there as example to avoid the previous step. Now, I would like to pass this callback function to my C# project. For this, I create a method in unmanaged C++, pass it to managed C++ and from this point pass it finally to C#. I'd like something like this:

// Unmanaged class
public class Wrapper
{
public:
    std::function<void(int)>callback;

    void ReturnToCallback(int data)
    {
        callback(data);
    }

    void PassCallback()
    {
        NETWrapper netWrapper;
        netWrapper.TestCallback(ReturnToCallback);
    }
};

//Managed class
public ref class NETWrapper
{
public:
    void TestCallback(Action<int>^ callback)
    {
       StartGenerator^ startGen = gcnew StartGenerator(callback);
    }
};

// C#
public class StartGenerator
{
    private Communication comm;

    public StartGenerator(Action<int> callback)
    {
        comm = Communication.Instance;
        comm.callback = callback;
    }
}

这种解决方案当然会给我带来错误编译时:

This solution, of course, gives me back an error when compiling:

的指针尝试了其他方法,例如获取函数指针的委托,以便我可以在Managed C ++上工作并将其传递给C#,但我无法正确实现它。您认为尝试此操作的最佳方法是什么?

I have tried other ways such as Get the delegate for the function pointer so I can work on Managed C++ and pass it to C# but I am not able to implement it right. What do you think is the best way to try this?

推荐答案


  1. 制作包装器::回调指向 std :: function 的指针。

  2. 将包装器更改为 ref class

  1. Make Wrapper::callback a pointer to the std::function.
  2. Change Wrapper to a ref class.

就是这样。

public ref class Wrapper
{
public:
    std::function<void(int)>* callback;

    void ReturnToCallback(int data)
    {
        (*callback)(data);
    }

    void PassCallback()
    {
        NETWrapper netWrapper;
        netWrapper.TestCallback(gcnew Action<int>(this, &Wrapper::ReturnToCallback));
    }
};

然后您需要管理 std :: function 现在,也许可以向您展示如何做到这一点。

You do then need to manage the lifetime of the std::function now, perhaps my clr_scoped_ptr could show you how to do that.

这篇关于将非托管方法作为回调传递给托管C ++ / CLI类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 01:09