【问题标题】:How to call a function declared in mainpage.xaml.cpp如何调用在 mainpage.xaml.cpp 中声明的函数
【发布时间】:2015-03-26 00:20:50
【问题描述】:

基本上:

MainPage.xaml.h 在 MainProject 中引用 WrapperProject

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

Wrapper.h 在 WrapperProject

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

Wrapper如何调用DoAGreatThing方法?


改为文字墙:

我有一个包含多个项目的 Win8 应用程序。主应用项目是默认的基于 XAML 的 C++/CX 项目。

包装器项目有一个单例,它的文件包含在 mainpage.xaml 中,在某些情况下可以调用包装器方法。

我引用了一些只能在主应用程序项目中引用的库,因此只能从那里调用它的方法,但包装器看不到这些文件 (mainpage.xaml)。我的包装器中不能包含主页,但是当其他项目中发生事件时,我需要从上述库中调用一些方法,它应该由包装器传递。

我未能在 mainpage.xaml.cpp 中创建函数指针并将其传递给包装器单例,因为它是 C++/CX 并且它不喜欢原生类型。

我未能创建委托/事件,但委托声明应该在 mainpage.xaml.h 中完成,因此包装器看不到。

我该怎么办?如何从 wrapper 调用 mainpages 函数?

【问题讨论】:

  • 您能否发布一个您想要实现的目标的示例?
  • @robwirving 添加了一个“样本”

标签: c++ windows-8 c++-cx


【解决方案1】:

我解决了这个问题:

App.xaml.cpp(了解 MainPage 并将其作为 mMainPage)

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

NativeClass.h 位于 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;
//...
}

从 NativeClass 调用 DoAGreatThing 调用 MainPages DoAGreatThing

所有赞美 lambdas!

【讨论】:

    猜你喜欢
    • 2012-10-30
    • 1970-01-01
    • 2021-04-21
    • 2012-12-20
    • 1970-01-01
    • 2012-08-03
    • 2013-07-30
    • 1970-01-01
    • 2019-07-05
    相关资源
    最近更新 更多