Search code examples
c++windows-8c++-cx

How to call a function declared in mainpage.xaml.cpp


Basically:

MainPage.xaml.h in MainProject that references WrapperProject

#includes yadda-yadda
#include "Wrapper.h"
namespace MyNamespace
{
    public ref class MainPage sealed
    {
    public:
        MainPage();
        //...
        DoAGreatThing(int greatThingId);
    private:
        //...
    }

Wrapper.h in WrapperProject

#include "pch.h"
ref class Wrapper sealed
{
public:
    static void InitInstance();
    static Wrapper^ instance();
    //...
}

How can Wrapper call DoAGreatThing method?


Wall of text instead:

I have a Win8 application with several projects. Main app project is default XAML-based C++/CX project.

Wrapper project has a singleton and its files are included in mainpage.xaml to call wrapper methods in some cases.

I've referenced some library that must be referenced only in main app project and thus its methods can be called only from there, but wrapper doesn't see these files (mainpage.xaml). I cannot include mainpage in my wrapper, but I need to call some methods from aforementioned library when an event occurs in other projects, it should be passed by wrapper.

I failed to create a function pointer in mainpage.xaml.cpp and pass it to wrappers singleton since it's C++/CX and it doesn't like native types.

I failed to create a delegate/event but a delegate declaration should've been done in mainpage.xaml.h and thus wouldn't be visible to wrapper.

What should I do? How can I call a mainpages function from wrapper?


Solution

  • I solved the problem:

    App.xaml.cpp (that knows about MainPage and has it as mMainPage)

    void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ args)
    {
    //...
    NativeClass::instance()->SetGreatThingDoer([=](int greatThingId){mMainPage->DoAGreatThing(greatThingId);});
    //...
    }
    

    NativeClass.h that lies beside wrapper in WrapperProject

    #include <functional>
    //...
    class NativeClass
    {
    public:
        void SetGreatThingDoer(std::function<void(int)> func) {mDoAGreatThing = func;};
        void DoAGreatThing(int greatThingId) {mDoAGreatThing(greatThingId);};
    private:
        std::function<void(int)> mDoAGreatThing;
    //...
    }
    

    Calling DoAGreatThing from NativeClass calls MainPages DoAGreatThing

    All praise lambdas!