Andrew
Andrew

Reputation: 23

how to write C++ code to handle an event raised in C# code

I would like to know how, in C++ code, can i receive and then handle events raised from C# code.

I have a C# WinForms UI module that raises an event after collecting some information. I have to handle the event in C++ code, because that's where the code to process the collected information is already implemented. I just need the code that will catch the event, and extract the information associated with it. I'm working in VS2010, and the C++ code is an MFC app, in case that's useful info.

Thank you.

Upvotes: 2

Views: 3269

Answers (3)

Ben Jackson
Ben Jackson

Reputation: 93940

I pulled up a project I knew to mix C# and C++ with events, but the code I have is actually backwards from what you want: It fires C# delegates from C++. There might be enough keywords to point you in the right direction:

    public: static void Fire(Delegate^ del, ... array<System::Object^>^ args)
    {
        if (nullptr == del)
            return;

        array<Delegate^>^ delegates = del->GetInvocationList();

        for each (Delegate^ sink in delegates)
        {
            try
            {
                //sink->DynamicInvoke(args);
                System::Windows::Forms::Form^ f;
                f = dynamic_cast<System::Windows::Forms::Form^>(sink->Target);
                if (f) {
                    f->Invoke(sink, args);
                } else {
                    sink->DynamicInvoke(args);
                }
            }
            catch(Exception^ e)
            {
                Trace::WriteLine("EventsHelper.Fire");
                Trace::WriteLine(e->Message);
            }

        } // end for each

    } // end Fire

Upvotes: 0

David Yaw
David Yaw

Reputation: 27894

You may want to go through C++/CLI on your way from C# to C++.

You could write a C++/CLI wrapper which would, in a managed method, call the unmanaged C++ code directly. Handle any conversions (data types, System.String to char*, for example) in the C++/CLI managed method. In C#, that C++/CLI code will show up as any other external assembly does, call it wherever you need to.

I think part of the issue is exactly how the C# Winforms project relates to the C++ MFC project. If the C++ code a simple processing library, then a C++/CLI wrapper sounds correct to me. If the C++ app is the primary, and it's loading the C# project to collect that information, then something else may be better.

Upvotes: 1

Aaron
Aaron

Reputation: 36

Check out delegate/function pointer interop. http://msdn.microsoft.com/en-us/library/367eeye0(v=VS.100).aspx

You could also attach a C# delegate to the event and have the C# code call the C++ code via P/Invoke.

Upvotes: 2

Related Questions