QT run objective-c code

前端 未结 1 405
别那么骄傲
别那么骄傲 2021-01-03 00:49

I\'m trying to run native object-c code on my Mac application.

My code looks like:

MainWindow.h:

#ifdef Q_OS_MAC
    #includ         


        
1条回答
  •  情深已故
    2021-01-03 01:00

    In order to compile objective-c with C++, you need to have the objective-c code in a .m or .mm file.

    The accompanying header can then contain functions that can be called from C++ and the body of those functions can contain objective-c code.

    So let's say, for example, we wanted to call a function to pop up an OSX notification. Start with the header: -

    #ifndef __MyNotification_h_
    #define __MyNotification_h_
    
    #include 
    
    class MyNotification
    {
    public:
        static void Display(const QString& title, const QString& text);    
    };    
    
    #endif
    

    As you can see, this is a regular function in a header that can be called from C++. Here's the implementation:-

    #include "mynotification.h"
    #import 
    #import 
    
    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];
    }
    

    The implementation contains objective-c and due to its .mm file extension, the compiler will handle this correctly.

    Note that in the example you provide in the question, you need to think about what the code is doing; especially when using 'self', as I expect that would need to refer to an Objective-C class, not a C++ class.

    0 讨论(0)
提交回复
热议问题