Rodhos Soft

備忘録を兼ねた技術的なメモです。Rofhos SoftではiOSアプリ開発を中心としてAndroid, Webサービス等の開発を承っております。まずはご相談下さい。

Objective-C++でクラス

JSONを使った受け渡しを想定して書いてみた。非効率かも。

#import <Foundation/Foundation.h>

@class Engine;

typedef NSDictionary JSON;

@protocol EngineProtocol <NSObject>
- (void)engine:(nonnull Engine *)engine message:(nonnull JSON *)message;
@end

@interface Engine : NSObject
+ (nonnull instancetype)engine:(nonnull id <EngineProtocol>)delegate;
- (void)tellMessage:(nonnull JSON *)message;
@end

#include <stdio.h>
#include <iostream>

class EngineCpp;




class EngineCpp {
public:
    EngineCpp();
    ~EngineCpp();
    void hello();
    typedef std::shared_ptr<EngineCpp> Ptr;
    std::string message;
    std::string proc(std::string src);
};

EngineCpp::EngineCpp() {
    std::cout << "EngineCpp new" << std::endl;
}

EngineCpp::~EngineCpp() {
    std::cout << "EngineCpp delete" << std::endl;
}

void EngineCpp::hello() {
    std::cout << "EngineCpp hello" << std::endl;
}

std::string EngineCpp::proc(std::string src) {
    return "{\"Hello\":" + src + "}";
}

@interface NSJSONSerialization(String)
+ (NSString *)jsonString:(NSDictionary *)dic;
+ (NSDictionary *)jsonString_r:(std::string &)str;
@end

@implementation NSJSONSerialization(String)
+ (NSString *)jsonString:(NSDictionary *)dic {
    NSData *d = [NSJSONSerialization dataWithJSONObject:dic
                                                options:NSJSONWritingPrettyPrinted
                                                  error:nil];
    NSString *sd = [[NSString alloc] initWithData:d
                                         encoding:NSUTF8StringEncoding];
    return sd;
}

+ (NSDictionary *)jsonString_r:(std::string &)str {
    NSData *data = [NSData dataWithBytes:str.c_str() length:str.length()];
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data
                                                        options:NSJSONReadingMutableContainers                                                          error:nil];
    return dic;
}

@end




@interface Engine()
@property (nonatomic) id <EngineProtocol> delegate;
@property (nonatomic, assign) EngineCpp::Ptr engineCpp;
@end


@implementation Engine {
}

- (void)dealloc {
    NSLog(@"Engine dealloc");
}

+ (instancetype)engine:(id<EngineProtocol>)delegate {
    Engine *engine = [Engine new];
    engine.delegate = delegate;
    engine.engineCpp = std::make_shared<EngineCpp>();

    return engine;
}


- (void)tellMessage:(JSON *)message {

    std::string str = [NSJSONSerialization jsonString:message].UTF8String;
    
    std::string result = self.engineCpp->proc(str);
    
    NSDictionary *dic = [NSJSONSerialization jsonString_r:result];
    
    [self.delegate engine:self message:dic];
}

@end