C++ in iOS – 2

Continuing from the previous post. This one will look into a working example for the same. The code used here is pretty trivial. It is organized in the following sets of files. A c++ header file which contains the declaration of a class. A c++ implementation file (.cpp) where the member functions are implemented. An Objective-C++ header file which holds the C wrapper struct & an Objective-C wrapper object. An Objective-C++ implementation file (.mm) which implements the C struct & all the member functions for both the C struct as well as the Objective-C class.

CppStruct.h


#include <string>
class MyObject
{
     public:
          std::string getName();
          void setName(std::string tempName);
          MyObject();
      private:
           std::string name;
 };

CppStruct.cpp

#include "CppStruct.h"
#include <string>
#include <iostream>

std::string MyObject::getName()
{
     return name;
}

void MyObject::setName(std::string tempName)
{
     name = tempName;
}

MyObject::MyObject()
{
     name = "NIL";
}

CppStructWrapper.h

struct PersonWrapper;

@interface CppStructWrapper : NSObject
{
     struct PersonWrapper *obj;
}

-(void) makeAPerson;
-(void) setName:(NSString *) personName;
-(NSString *) getName;
@end

CppStructWrapper.mm

#import "CppStructWrapper.h"
#include "CppStruct.h"
#include <string>

@implementation CppStructWrapper

struct PersonWrapper
{
     MyObject *personObj;
     std::string getName();

     void setName(std::string tempName);
     PersonWrapper();
};

std::string PersonWrapper::getName()
{
     return personObj->getName();
}

void PersonWrapper::setName(std::string tempName)
{
     personObj->setName(tempName);
}

PersonWrapper::PersonWrapper()
{
     personObj = new MyObject;
}

-(id) init
{
     self = [super init];
     if(self)
     {
          obj = nil;
     }
     return self;
}

-(void) makeAPerson
{
     obj = new PersonWrapper;
}

-(void) setName:(NSString *) personName
{
     std::string temp([personName UTF8String]);
     obj->setName(temp);
}

-(NSString *) getName
{
     NSString *str = [[NSString alloc] initWithUTF8String:obj->getName().c_str()];
     return str;
}

@end

ViewController.m

//this code could be anywhere I have put it inside the ViewController.m within the init message.
#import "ViewController.h"
#import "CppStructWrapper.h"

-(id) init
{
     self = [super init];
     if(self)
     {
          CppStructWrapper *obj = [[CppStructWrapper alloc] init];
          [obj makeAPerson];
          [obj setName:@"ABC"];
          NSString *str = [obj getName];
          NSLog(@"%@",str);
     }
     return self;
}

 

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s