Question

For those of you who have successfully been able to call C++ code from Objective-C, will you please enlighten me?

This link says you need to wrap your C++ code using a technique he describes in his article. It looks good but I still have problems.

This link says that as long as the Objective-C class calling the C++ class has been converted to a .mm (Objective-C++) class then the two should work nicely together.

Each of these approaches are causing me grief the minute I try to add a method call. Can somebody please give me code for a simple Hello World iOS app that uses Objective-C for the "Hello" part and a C++ class for the "World" part with an Objective-C++ class in the middle? Or do I still have the entire concept wrong?

Was it helpful?

Solution

Essentially you need an ObjC class with .mm extension that calls an ObjC class with .mm extension. The second one will be used as a C++ wrapper class. The wrapper class will call your actual .cpp class. It's a little tricky, so I'm going to give you some verbose code. Here is an overview of the project:

enter image description here

In your ObjC code (ViewController) you would call the CplusplusMMClass

- (IBAction)buttonPushed:(UIButton *)sender {
    self.mmclass = [[CplusplusMMClass alloc]init];  // bad practice; but showing code
    NSString *str = [self.mmclass fetchStringFromCplusplus];
    [self populateLabel:str];
}

Here is the CplusplusMMClass .h and .mm

#import <Foundation/Foundation.h>
#import "WrapperClass.h"

@interface CplusplusMMClass : NSObject
@end

@interface CplusplusMMClass()
@property (nonatomic, strong) WrapperClass *wrapper;
- (NSString*)fetchStringFromCplusplus;
@end

#import "CplusplusMMClass.h"
#import "WrapperClass.h"

@implementation CplusplusMMClass

- (NSString*)fetchStringFromCplusplus {
    self.wrapper = [[WrapperClass alloc] init];
    NSString * result = [self.wrapper getHelloString];
    return result;
}

@end

Here is WrapperClass .h and .mm

#ifndef HEADERFILE_H
#define HEADERFILE_H

#import <Foundation/Foundation.h>

#if __cplusplus

#include "PureCplusplusClass.h"

@interface WrapperClass : NSObject
@end

@interface WrapperClass ()
- (NSString *)getHelloString;
@end


#endif
#endif

#import "WrapperClass.h"

#include "WrapperClass.h"
#include "PureCplusplusClass.h"

using namespace test;

@interface WrapperClass ()
@property (nonatomic) HelloTest helloTest;
@end

@implementation WrapperClass

- (NSString *)getHelloString {
    self.helloTest = *(new HelloTest);
    std::string str = self.helloTest.getHelloString();
    NSString* result = [[NSString alloc] initWithUTF8String:str.c_str()];
    return result;
}

@end

Here is the PureCplusplusClass .h and .cpp

#ifndef __HelloWorld__PureCplusplusClass__
#define __HelloWorld__PureCplusplusClass__

#include <stdio.h>
#include <string>

using namespace std;

namespace test {
    class HelloTest
    {
    public:
        std::string getHelloString();
    };
}

#endif /* defined(__HelloWorld__PureCplusplusClass__) */

#include <stdio.h>
#include <string>

std::string test::HelloTest::getHelloString() {
    std::string outString = "Hello World";
    return outString;
}

This code is not perfect! I'm having trouble with the namespace test being recognized. I'll update when I can.

But this should get you there!!!!

OTHER TIPS

Another (contrived) one:

Use a C++ class as an ivar:

File Foo.h

#import <Foundation/Foundation.h> 

@interface Foo : NSObject
@property (nonatomic, readonly) NSString* what;
@end

File: Foo.mm

#import "Foo.h"
#include <string>

@implementation Foo {
    std::string _string;  // C++ class must have a default c-tor
}

- (id)init
{
    self = [super init];
    if (self) {
        _string = "Hello, World!"
    }
    return self;
}

- (NSString*) what {
    NSString* result = [[NSString alloc] initWithBytes:_string.data()
                                                length:_string.size() 
                                              encoding:NSUTF8StringEncoding];
    return result;
}

@end

Note:

An executable may need to explicitly link against the C++ library, e.g. by adding an additional flag to "Other Linker Flags": -lc++

Alternatively, the main.m file can be renamed to main.mm.

The latter is more robust in selecting the "correct" library, since the tool chain will do that itself. But perhaps, for anyone else examining the project, a renamed "main.m" may not be that obvious and may cause confusion.

I ran into this situation with xcode 12.4, needing to use an existing C++ class "CppModule" in an objective-c project. Here is what I did.

  1. First problem was that #include in CppModule.hpp gave a compiler error: 'string' file not found. Fixed that by wrapping the .hpp file contents in
#if defined __cplusplus
  declarations
#endif
  1. Then string var declarations gave another compiler error: Unknown type name 'string'; did you mean 'std::string'? Fixed that by:
#include <string> 
using namespace std;
  1. The C++ CppModule.cpp, the CppModule.hpp include file, the calling objective-c module.m, and it's module.h files MUST all be set as Type "Objective-C++ Source", using xcode's Inspector (top right in the editor window). Renaming module.m to module.mm also sets the type to "Objective-C++ Source" (xcode 12.4). Perhaps good to use .mm, as a reminder it calls C++.

In the module.h file include the C++ header:

#include < CppModule.hpp>
  1. Odd (to me) is that in the module.h file "CppModule" is not recognised as a known type, so you cannot declare vars or properties of that type in your module.h, but in the module.m(m) file it is a known type. In the module.mm file, after the @implementation add:
static CppModule *module_cpp;
  1. Now you can, e.g. in the module.mm's init, call the C++ module's initialiser, like:
module_cpp = new CppModule(parameters);

And the C++ module remains accessible via that static module_cpp *pointer.

  1. Call the module.cpp's methods (example) in your objective-c method:
CppModule::Result r = module_cpp->CppMethod();

Appears to work absolutely fine!

If anyone can explain the oddities in 4. I'd be grateful.

The module I needed just does some complex (numeric) calculations, and I did not feel like converting that code to Objective-C.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top