I’m interested in calling a C# method from C++ code in Windows Phone 8. I have already learned how to pass a callback function to C++ code from C# via delegate declarations in my C++ code, but I am looking to see if I can do any of the following:
-
Call certain methods directly from the C++ code. This would involve somehow inspecting the C# object makeup from C++, and seems unlikely to me, but I thought I’d ask you all anyway
-
Trigger events in the C# code, which can then be handled by C# methods
-
Use a dispatcher to call C# callbacks in the Main UI thread so that the callbacks can modify UI elements
-
Use a dispatcher to trigger events in the C# code, (Essentially a merging of the above two points)
In short, I am looking for as many C++ –>C# communication tips as you guys can throw me, I want to learn it all. 🙂
By getting an object in C# code to implement a Windows RT interface, and passing down a reference to this object, it is possible to do all of the above with a bit of set-up (if I understand correctly – not sure about exactly what you want to do with your Dispatcher examples – you might want to wrap the Dispatcher on the C# side).
public interface classin a C++/CX header for the C# to implement (C++ to call) (e.g.ICallback).public ref classin a C++/CX header for the C++ to implement (C# to call) (e.g.CppCxClass).Add a method in
CppCxClassthat passes and stores anICallback. (A C++ global variable is shown for consiseness, I recommend you review this to see if you can find a better place to store this in your code-base).Reference the WinRT library in your C# code.
CppCxClassusingvar cppObject = new CppCxClass().ICallback(e.g.CSharpCallbackObject).CSharpCallbackObjectdown to C++. E.g.cppObject.SetCallback(new CSharpCallbackObject()).You can now call C# with
globalCallback->CallCsharp(L"Hello C#");. You should be able to extend eitherICallbackand/orCppCxObjectto do the rest of your tasks.