2

I am trying to call some C++ code in a Swift application. I did not write the C++ nor do I have control over it.

I have created a C++ wrapper to handle the calls from Swift. I also added some test functions within the C++ files to verify that I am calling the C++ from Swift. Those functions simply return an int.

In the C++ header code there is a function defined as follows:

class GlobeProcessor {
public:
    void readFile(ifstream &inputFile);
    // ...
};

In my wrapper I have defined the function as follows:

extern "C" void processGlobe(ifstream &file) {
    GlobeProcessor().readFile(file);
}

The confusing part is how to reference this in my bridging header. Currently the bridging header contains the following:

// test function
int getNumber(int num);

void processGlobeFile(ifstream &file);

The test function succeeds, so I am able to access the C++ from Swift. However, adding a declaration for processGlobeFileto the bridging header produces the following compile error:

Unknown type name 'ifstream'

I have tried unsuccessfully to add the appropriate imports to the bridging header. I am not a seasoned C++ guy, so i don't really know if I'm approaching this in the correct manner. Can somebody help me to understand how to pass a file as a parameter to a C++ method from Swift?

Thanks!

Pheepster
  • 6,045
  • 6
  • 41
  • 75

1 Answers1

2

Swift can't import C++. ifstream is a C++ class and the parameter is also a C++ reference. Neither of these are going to work with Swift.

You have to write a C function that wraps your C++ call and treats your ifstream object as an opaque reference.

Also your wrapper function has to be declared extern "C" not just defined that way, otherwise other C++ files that include the header will assume it has name mangling.

Something like this might work but I haven't tested it at all:

// header
#if !defined _cplusplus

typedef struct ifstream ifstream; // incomplete struct def for C opaque type

#else

extern "C" {

#endif

int getNumber(int num);

void processGlobeFile(ifstream *file); // note you need to use a pointer not a reference

#if defined __cplusplus

} // of the exten C

#endif
JeremyP
  • 84,577
  • 15
  • 123
  • 161