Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Cocoa function from C++

In the answer to this question: get logged in user the accepted answer uses Delphi code that looks like this to get access to the Cocoa function NSUserName.

function NSUserName: Pointer; cdecl; external '/System/Library/Frameworks/Foundation.framework/Foundation' name _PU +'NSUserName';

How would you do this in C++Builder?

like image 784
Gregor Brandt Avatar asked Oct 03 '22 13:10

Gregor Brandt


1 Answers


This answers the question and is worth the bounty

The solution is to import NSUserName in C++ by using dlopen and dlsym:

void* (*NSUserName)();
String UserName;
void *hLib = dlopen("/System/Library/Frameworks/Foundation.framework/Foundation", RTLD_GLOBAL);
if(hLib)
{
    NSUserName = (void*(*)())dlsym(hLib, "NSUserName");
    CFStringRef srUserName = (CFStringRef)NSUserName();
    if(srUserName)
    {
        UserName = CFStringGetCStringPtr(srUserName, 0);
    }
    dlclose(hLib);
}

It is possible to use NSString (Cocoa Type) directly in C++ Builder by adding a header file as:

#include <Macapi.Foundation.hpp> // note that this will cause 8080 warnings if you have this warning turned on (unused variables)

Now I can use NSString instead CFStringRef (Core Foundation Type):

UserName = TNSString::Wrap(NSUserName())->UTF8String();
like image 193
14 revs, 2 users 77% Avatar answered Oct 10 '22 02:10

14 revs, 2 users 77%