Alex Rivera | Logout

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

Asked 2012-09-17T21:27:14.020
11

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
Edit
Report

1 Answer

1

Just for kicks--I found a partial solution using templates, but I doubt you'll get much "real-world" mileage with it...

template <int X, const char Y[]>
class CPPClass
{
    int _x;
    const char * _string ;

public:
    CPPClass();
};

template <int X, const char Y[]>
CPPClass<X, Y>::CPPClass()
: _x(X)
, _string(Y)
{

}


extern const char kHelloWorld[] = "hello world";

@interface MyObject : NSObject
{
    CPPClass<5, kHelloWorld> thing;
}

@end

Note that the int template parameter can be a literal in place, but the const char[] template parameter must be declared in a variable with external linkeage.. (according to clang)

answered 2012-09-17T22:32:52.757

Your Answer