I am currently trying to use a piece of code I have written in c++ in an iphone application. I have read about wrapping C++ code using objective-C++. the c++ function I am trying to call takes for arguments 2 std::string and returns a std::string:
// ObjCtoCPlusPlus.mm
#import <Foundation/Foundation.h>
#include "CPlusPlus.hpp"
#import "ObjCtoCPlusPlus.h"
@implementation Performance_ObjCtoCPlusPlus : NSObject
- (NSString*) runfoo: (NSString*)list
{
std::string nodelist = std::string([[list componentsSeparatedByString:@"*"][0] UTF8String]);
std::string lines = std::string([[list componentsSeparatedByString:@"*"][1] UTF8String]);
std::string result = Performance_CPlusPlus::run(nodelist, lines);
return [NSString stringWithCString:result.c_str()
encoding:[NSString defaultCStringEncoding]];
}
- (void) exp
{
Performance_CPlusPlus::explanation();
}
@end
I am calling the objective-C++ function from swift
// I am calling the function from the viewController.swift
@IBAction func button(sender: AnyObject) {
let z : String = "0 1/1 2";
let q : String = "a b Y";
let x = Performance_ObjCtoCPlusPlus.runfoo((q + "*" + z) as NSString)
}
error:Cannot convert value of type NSString to expected argument type PerformanceObjCtoCPlusPlus. I think the error I am getting is because I cannot convert the String type of swift to a NSString*. is there any work-around to solve this problem?
You rather need to perform object than class method:
let z : String = "0 1/1 2";
let q : String = "a b Y";
let obj = Performance_ObjCtoCPlusPlus()
let res = obj.runfoo(q + "*" + z)
print(res)
And one another observation - you don't need cast String to NSString. Swift's interoperability with Obj-C does it for you for free.
BTW, I use Swift 2.2