Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++-cli

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

like image 382
anivas Avatar asked Oct 26 '10 16:10

anivas


1 Answers

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
    }
};
like image 74
mcdave Avatar answered Sep 20 '22 23:09

mcdave