How to sink an event from C++.NET in C#?

  • Thread starter Thread starter Dejun Yang
  • Start date Start date
D

Dejun Yang

Could anybody help me?
How to sink an event from C++.NET in C#? For example, for
following CSource, how to sink EventTest in C#?

#pragma once
#include <windows.h>
using namespace System;

namespace CSource
{
[event_source(managed)]
public __gc class CSourceClass
{
// TODO: Add your methods for this class here.
public:
CSourceClass(void){}
~CSourceClass(void){}

void FireEvent()
{
__raise EventTest();
}

__event void EventTest();
};
}

Thank you very much,

Ydejun
 
Dejun Yang said:
Could anybody help me?
How to sink an event from C++.NET in C#? For example, for
following CSource, how to sink EventTest in C#?

Since your code is a managed class (__gc) you do not need to use
[event_source(managed)]. This attribute is *not* a .NET attribute, it is a
compile time attribute only recognized by the C++ compiler. [event_source()]
is useful for COM events and for native events (ie neither .NET nor COM).

Instead, you simply have to define an event in the class, as you have done.
I have added some other comments:
#pragma once

this is in a header file, yes?
#include <windows.h>

does the code really use Win32? you might have Win32 code, but if you don't
your code will compile quicker without this line

you have included a line like the following, somewhere in your project?

#using said:
using namespace System;

namespace CSource
{
public __gc class CSourceClass
{
public:
CSourceClass(void){}
~CSourceClass(void){}

Don't give a managed class a destructor unless you really do need it. The
reason is that a destructor will make objects live longer than they need to,
and hence it will use up resources. Since your code has an empty destructor,
you should remove it entirely.
void FireEvent()
{
__raise EventTest();
}

__event void EventTest();
};
}

There is a problem with this approach, however. The problem is that
declaring the event like this means that the delegate is also declared
within the class and the compiler generates a name for it. In this case the
delegate is called

CSource.CSourceClass.__Delegate_EventTest

This is not easy to remember! It would be far better to declare the delegate
outside of the class. Here is the cleaned up version:

namespace CSource
{

public __delegate void MyEvent();
public __gc class CSourceClass
{
public:
__event MyEvent EventTest;
CSourceClass(void){}
void FireEvent()
{
__raise EventTest();
}
};

}

using this from C# is simple:

CSourceClass obj = new CSourceClass();
// assume EventHandler is a member method
MyEvent ev = new MyEvent(EventHandler);
obj.EventTest += ev;
obj.FireEvent();

Richard
 
Back
Top