【问题标题】:QT run objective-c codeQT运行objective-c代码
【发布时间】:2014-05-01 08:05:56
【问题描述】:

我正在尝试在我的 Mac 应用程序上运行本机 object-c 代码。

我的代码如下:

MainWindow.h:

#ifdef Q_OS_MAC
    #include <Carbon/Carbon.h>
    #include <ctype.h>
    #include <stdlib.h>
    #include <stdio.h>

    #include <mach/mach_port.h>
    #include <mach/mach_interface.h>
    #include <mach/mach_init.h>

    #include <IOKit/pwr_mgt/IOPMLib.h>
    #include <IOKit/IOMessage.h>
#endif

MainWindow.cpp:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);


    #ifdef Q_OS_MAC
    [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver: self
            selector: @selector(receiveSleepNote:)
            name: NSWorkspaceWillSleepNotification object: NULL];
    #endif

}

#ifdef Q_OS_MAC
- (void) receiveSleepNote: (NSNotification*) note
{
    NSLog(@"receiveSleepNote: %@", [note name]);
}
#endif

但是我得到的错误似乎是 QT 不理解代码结构:

application.cpp:错误:预期的外部声明 - (void) receiveSleepNote: (NSNotification*) note ^

【问题讨论】:

标签: objective-c qt


【解决方案1】:

为了使用 C++ 编译 Objective-c,您需要将 Objective-c 代码保存在 .m 或 .mm 文件中。

随之而来的标头可以包含可以从 C++ 调用的函数,并且这些函数的主体可以包含 Objective-C 代码。

假设,例如,我们想要调用一个函数来弹出 OSX 通知。从标题开始:-

#ifndef __MyNotification_h_
#define __MyNotification_h_

#include <QString>

class MyNotification
{
public:
    static void Display(const QString& title, const QString& text);    
};    

#endif

如您所见,这是可以从 C++ 调用的标头中的常规函数​​。这是实现:-

#include "mynotification.h"
#import <Foundation/NSUserNotification.h>
#import <Foundation/NSString.h>

void MyNotification::Display(const QString& title, const QString& text)
{
    NSString*  titleStr = [[NSString alloc] initWithUTF8String:title.toUtf8().data()];
    NSString*  textStr = [[NSString alloc] initWithUTF8String:text.toUtf8().data()];

    NSUserNotification* userNotification = [[[NSUserNotification alloc] init] autorelease];
    userNotification.title = titleStr;
    userNotification.informativeText = textStr;

    [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:userNotification];
}

该实现包含objective-c,并且由于其.mm 文件扩展名,编译器将正确处理。

请注意,在您在问题中提供的示例中,您需要考虑代码在做什么;尤其是在使用“self”时,正如我所料,它需要引用一个 Objective-C 类,而不是 C++ 类。

【讨论】:

  • 在我的 Qt 应用程序中 [NSUserNotificationCenter defaultUserNotificationCenter] 总是返回 nil。你知道可能是什么问题吗?我在 OS X 10.10 上使用 Qt 5.4.1
  • @user1113852 抱歉,我无法告诉您的信息很少。我建议就此提出一个新的 SO 问题。
  • 我已经发布了一些与此相反的问题——how to include and call a a Qt/C++ Dylib from within an Objective C Cocoa application。然而,截至 2015 年 12 月 9 日,我仍然没有答案。
  • 这是从 c++ 调用 objc 的最佳方式,在 SO 中有一个类似的答案,其中有很多赞成票,这太复杂了。
  • 看起来您没有链接到 Foundation 框架。
猜你喜欢
  • 2018-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-20
  • 1970-01-01
  • 1970-01-01
  • 2011-06-20
相关资源
最近更新 更多