Search code examples
cobjective-cnsstringnshomedirectory

Get NSHomeDirectory() in pure C


I am trying to get the NSHomeDirectory() in pure C

#include <CoreFoundation/CFBundle.h>
#include <CoreFoundation/CoreFoundation.h>

void testFunc() {
    printf(NSHomeDirectory()); 
}

Solution

  • You need to send the UTF8String message to the NSString object returned by NSHomeDirectory() to obtain a C string. To do this in pure C (Tested):

    #include <objc/runtime.h>
    #include <objc/message.h>
    void *NSHomeDirectory();
    void testFunc() {
        puts(((const char *(*)(void *, SEL))objc_msgSend)(NSHomeDirectory(), sel_getUid("UTF8String")));
        // Also use puts() instead of printf() here
    }
    

    Note: Compile using -framework Cocoa