无法在非托管代码中使用托管事件/对象错误c3265,c2811 [英] Cannot use managed event/objects in unmanaged code error c3265, c2811

查看:507
本文介绍了无法在非托管代码中使用托管事件/对象错误c3265,c2811的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++ / CLI项目中使用的本机C ++库引发了给我结果的事件,

Native C++ library that I am using in C++/CLI project raises events giving me results,


  • 如果我尝试处理事件通过扩展非托管事件,它说ref类只能扩展ref类。

  • 然后我尝试创建一个本机事件,但在其中有manged对象来收集结果,但我得到该错误不能在非托管类中声明托管对象。

无论如何,要以我尝试的方式之一完成,我应该声明非托管结果对象在非托管事件中填充,然后Marshall吗?

Is there anyway to get it done in one of the ways I am trying, or should I declare unmanaged result objects fill them in unmanaged event and then Marshall it ?

编辑

class MyNativeListener: public NativeEventListener
{ 
private:
    ManagedResultsObject ^_results;
public:

void onEndProcessing(ProcessingEvent *event) 
{
    _results.Value = event->value;
      //Many more properties to capture

}

};

这是我想要的,我已经扩展本机事件侦听器捕获事件,确保如何将结果捕获到托管对象。

This is what I am trying, I have extended the native event listener to capture the event, but not sure how to capture the results to a managed object.

Edit2
在@ mcdave auto_gcroot

推荐答案

您的本地类需要存储托管对象的句柄而不是对它的引用。您可以使用 gcroot模板来执行此操作。如果你深入gcroot模板,你会发现它使用 GCHandle结构,它使用适当的静态转换可以存储为 void * 指针,因此提供了在本地代码中存储托管引用的方法。

Your native class needs to store a handle to the managed object instead of a reference to it. You can do this using the gcroot template. If you dig into the gcroot template you will find it uses the GCHandle Structure, which with appropriate static casting can be stored as a void* pointer and so provides a means of storing managed references in native code.

尝试沿着以下行扩展您的代码:

Try expanding your code along the following lines:

#include <vcclr.h>

class MyNativeListener: public NativeEventListener
{ 
private:
    gcroot<ManagedResultsObject^> _results;
public:
    void onEndProcessing(ProcessingEvent *event) 
    {
        _results->Value = event->value;
        //Many more properties to capture
    }
};

这篇关于无法在非托管代码中使用托管事件/对象错误c3265,c2811的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆