Cannot use managed event/objects in unmanaged code error c3265, c2811

戏子无情 提交于 2019-11-30 17:31:06

问题


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

  • If I try to handle the event by extending the unmanaged event, it says the ref class can only extend ref class.
  • I then tried to create a native event but have manged object inside it to collect the results, but I get the error cannot declare managed object in unmanaged class.

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 ?

Edit:

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 Found this while searching on the same line as suggested by @mcdave auto_gcroot


回答1:


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
    }
};


来源:https://stackoverflow.com/questions/4025967/cannot-use-managed-event-objects-in-unmanaged-code-error-c3265-c2811

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