Solved 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,
- create a new file with .mm extension
- write your c ++ function in it
- call it from your Qt app
example:
MacUtils.hclass MacUtils { MacUtils() {} public: static QString localizedHostName(); };
#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,
- create a new file with .mm extension
- write your c ++ function in it
- call it from your Qt app
example:
MacUtils.hclass MacUtils { MacUtils() {} public: static QString localizedHostName(); };
#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?
-
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.
-
I add this to my .pro :
macx { # l'accolade doit se trouver sur la même ligne, sinon erreur sur linux LIBS += -framework AppKit }