Search code examples
c++objective-cmacosobjective-c++

Launching an open dialog on Mac OSX from C++


I have a header file that contains the code

#ifndef PLATFORM_DEPENDENCE
#define PLATFORM_DEPENDENCE

#define USE_MAC
#include "WindowsFunctions.h"
#include "MacFunctions.h

#endif

WindowsFunctions.h:

#ifndef WINTRANSFERINCLUDE
#define WINTRANSFERINCLUDE
#ifdef USE_WINDOWS

#include <string>
#include <boost/shared_ptr.hpp>

using namespace std;

#include <windows.h>
#include <Shlobj.h>

boost::shared_ptr<wstring> browseFolder();
boost::shared_ptr<vector<wstring>> getFilesInDirRecursiveImplementation(boost::shared_ptr<vector<wstring>> dirs, boost::shared_ptr<vector<wstring>> files);

#endif
#endif

and MacFunctions.h:

#ifndef MACTRANSFERINCLUDE
#define WACTRANSFERINCLUDE
#ifdef USE_MAC

#include <string>
#include <boost/shared_ptr.hpp>

using namespace std;

boost::shared_ptr<wstring> browseFolder();
boost::shared_ptr<vector<wstring>> getFilesInDirRecursiveImplementation(boost::shared_ptr<vector<wstring>> dirs, boost::shared_ptr<vector<wstring>> files);

#endif
#endif

The WindowsFunctions.cpp is already implemented, and works. How would I do it for Mac? I have written a method that opens up an open dialog, but I have no idea how to return the data to where it was called in C++.

This is the code that opens the dialog:

#import <Cocoa/Cocoa.h>
#include <string>

std::string* path() {
    NSOpenPanel *op = [NSOpenPanel openPanel];
    if ([op runModal] == NSOKButton) {
            NSURL *nsurl = [[op URLs] objectAtIndex:0];
            // nsurl.path contains the NSString I want to return as std::string
    }
    // ???
    return something;
}

How would I do this, or am I approaching the problem in a wrong way?


Solution

  • It's a bit long-winded, but here it is:

    std::string([[nsurl path] UTF8String]);
    

    Edit: Ok, so maybe not that long-winded.