Swift – C++ interop

It looks Swift can’t call C++ directly and need to call it via Objective-C++.

Swift Button Handler calls ObjectiveC class ObjCHoge’s functions as below.

@IBAction func buttonClicked(sender : AnyObject) {
    let date = NSDate()
    let formatter = NSDateFormatter()
    formatter.timeStyle = .LongStyle
    
    let a:Int32 = 10
    let b:Int32 = 20
    let hoge = ObjCHoge()
    
    var str = String(format: "[%@] %d+%d=%d\n", formatter.stringFromDate(date), a, b, hoge.add(a,b))
    insertMessage(str)
    str = String(format: "[%@] %d-%d=%d\n", formatter.stringFromDate(date), a, b, hoge.sub(a,b))
    insertMessage(str)
}

BridgingHeader.h should have pure Objective-C++ header which I think can’t have C++ classes.

#import "ObjCHoge.h"

Then ObjCHoge.h/.mm calls CppHoge methods. I didn’t want to use “void*” for storing CppHoge instance, but it looked ObjCHoge.h should be pure Objective-C++ header and cannot have CHoge* for Swift to call.
Hm… Objective-C (OSX/iOS UI)/C# (Win UI)/Java (Android UI) – C++ (logic) is more handy than Swift (OSX/iOS UI)/C# (Win UI)/Java (Android UI) – C++ (logic) when writing cross platform code for OSX/iOS.

Let me know if there is a better way.

#import <Foundation/Foundation.h>

@interface ObjCHoge : NSObject
{
    // it looks ObjCHoge.h should be pure Objective-C for Swift to call
    // and can't define CppHoge* _cppHoge
    void* _cppHoge;
}

-(int)add:(int)a :(int)b;
-(int)sub:(int)a :(int)b;
-(int)static_add:(int)a :(int)b;
-(int)static_sub:(int)a :(int)b;

@end

#include "ObjCHoge.h"
#include "CppHoge.h"

@implementation ObjCHoge
-(id)init{
    self = [super init];
    
    if (self) {
        _cppHoge = new CppHoge();
    }
    
    return self;
}

-(void)dealloc {
    delete static_cast<CppHoge*>(_cppHoge);
}

-(int)add:(int)a :(int)b {
    CppHoge& obj = *static_cast<CppHoge*>(_cppHoge);
    return obj.add(a, b);
}

-(int)sub:(int)a :(int)b {
    CppHoge& obj = *static_cast<CppHoge*>(_cppHoge);
    return obj.sub(a, b);
}

-(int)static_add:(int)a :(int)b {
    return CppHoge::static_add(a, b);
}

-(int)static_sub:(int)a :(int)b {
    return CppHoge::static_sub(a, b);
}
@end

CppHoge.h/.cpp

//
//  CppHoge.h
//

#ifndef __cp_osx__CppHoge__
#define __cp_osx__CppHoge__

#include <stdio.h>

class CppHoge
{
public:
    int add(int a, int b);
    int sub(int a, int b);
    static int static_add(int a, int b);
    static int static_sub(int a, int b);
};

#endif /* defined(__cp_osx__CppHoge__) */

//
//  CppHoge.cpp
//

#include "CppHoge.h"


int CppHoge::add(int a, int b){
    return a+b;
}

int CppHoge::sub(int a, int b){
    return a-b;
}

int CppHoge::static_add(int a, int b){
    return a+b;
}

int CppHoge::static_sub(int a, int b){
    return a-b;
}

Leave a Reply

Your email address will not be published. Required fields are marked *