Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to call macOS APIs from c++/qt application?



  • I need to call a native macOS API: NSHost to get localizedName of the mac but no idea how to call either Objective-C or Swift version of the API.

    PS. Don't know anything about objective-C or Swift, new to macOS development.



  • HI,

    1. create a new file with .mm extension
    2. write your c ++ function in it
    3. call it from your Qt app

    example:
    MacUtils.h

    class MacUtils
    {
    
    		MacUtils() {}
    
    	public:
    
        static QString  localizedHostName();
    };
    

    MacUtils.mm

    #import <Cocoa/Cocoa.h>
    #include "MacUtils.h"
    
    
    QString MacUtils::localizedHostName()
    {
        NSString* name=[[NSHost currentHost] localizedName];
    
        return QString::fromNSString(name);
    }
    

    Call it like this:

    #include "MacUtils.h"
    
    int main(int argc, char *argv[])
    {
        QString name=MacUtils::localizedHostName();
        qDebug()<<name;
    }
    

    For me prints: iMac de Jean



  • HI,

    1. create a new file with .mm extension
    2. write your c ++ function in it
    3. call it from your Qt app

    example:
    MacUtils.h

    class MacUtils
    {
    
    		MacUtils() {}
    
    	public:
    
        static QString  localizedHostName();
    };
    

    MacUtils.mm

    #import <Cocoa/Cocoa.h>
    #include "MacUtils.h"
    
    
    QString MacUtils::localizedHostName()
    {
        NSString* name=[[NSHost currentHost] localizedName];
    
        return QString::fromNSString(name);
    }
    

    Call it like this:

    #include "MacUtils.h"
    
    int main(int argc, char *argv[])
    {
        QString name=MacUtils::localizedHostName();
        qDebug()<<name;
    }
    

    For me prints: iMac de Jean



  • @mpergand Simple, to the point and it works. Merci!

    When I was trying to find a solution, noticed some people saying that I have to add framework reference in .pro file e.g.

    macx {
        LIBS += -framework CoreServices
        LIBS += -framework Foundation
        LIBS += -framework CoreFoundation
    }
    

    Your code works without the framework references. Are macOS framework references Not needed at all OR are they needed in some cases?


  • Lifetime Qt Champion

    Hi,

    It will depend on what API you use. If they fall in frameworks already used by Qt, they will already be part of the linker options.



  • @Taytoo

    I add this to my .pro :

    macx {   # l'accolade doit se trouver sur la même ligne, sinon erreur sur linux
    
     LIBS +=	-framework AppKit
    }
    

Log in to reply