Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a C++ constructor from an Objective-C class

How can I call a C++ constructor from inside an Objective-C class?

class CppClass {
public:
    CppClass(int arg1, const std::string& arg2): _arg1(arg1), _arg2(arg2) { }

    // ...
private:
    int _arg1; std::string _arg2;
};

@interface ObjC: NSObject {
    CppClass _cppClass;
}
@end

@implementation ObjC

- (id)init
{
    self = [super init];
    if ( self )
    {
         // what is the syntax to call CppClass::CppClass(5, "hello") on _cppClass?
    }
    return self;
}
@end
like image 973
syvex Avatar asked Sep 17 '12 21:09

syvex


1 Answers

If you're already using C++ in your ObjC, might as well make it a smart pointer, so you don't have to worry about adding the cleanup bits.

#include <memory>

@interface ObjC: NSObject {
    std::unique_ptr<CppClass> _cppClass;
}
@end

@implementation ObjC

- (id)init
{
    self = [super init];
    if ( self )
    {
         _cppClass.reset(new CppClass(5, "hello"));
    }
    return self;
}
@end
like image 189
Baxissimo Avatar answered Sep 28 '22 08:09

Baxissimo