我正在尝试在Mac应用程序上运行本机对象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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
但是正在收到似乎QT无法理解代码结构的错误:
application.cpp:错误:预期的外部声明-(void)receiveSleepNote:(NSNotification *)注意^
为了使用 C++ 编译 Objective-c,您需要在 .m 或 .mm 文件中包含 Objective-c 代码。
伴随的头文件可以包含可以从 C++ 调用的函数,这些函数的主体可以包含目标 C 代码。
例如,假设我们想调用一个函数来弹出 OSX 通知。从标题开始: -
#ifndef __MyNotification_h_
#define __MyNotification_h_
#include <QString>
class MyNotification
{
public:
static void Display(const QString& title, const QString& text);
};
#endif
Run Code Online (Sandbox Code Playgroud)
如您所见,这是一个头文件中的常规函数,可以从 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];
}
Run Code Online (Sandbox Code Playgroud)
该实现包含objective-c 并且由于其.mm 文件扩展名,编译器将正确处理它。
请注意,在您在问题中提供的示例中,您需要考虑代码在做什么;特别是在使用“ self ”时,因为我预计它需要引用一个 Objective-C 类,而不是一个 C++ 类。