1

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?

Marwan
  • 13
  • 2
  • 1
    Have you tried this? http://stackoverflow.com/questions/33118095/cannot-convert-value-of-type-string-to-expected-argument-type-error I am not familiar to objective c, but i dont think runfoo is a static method – Kit Fung Apr 16 '16 at 18:13

1 Answers1

0

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

Igor B.
  • 2,219
  • 13
  • 17
  • If that's necessary, I can share my sample app, which I used for the issue analysis. – Igor B. Apr 16 '16 at 18:56
  • I am having an error at the let res= obj.runfoo(q + "*" + z) line. Error: Cannot convert value of type 'String' to expected argument type '(UnsafePointer, UnsafePointer)' – Marwan Apr 16 '16 at 20:33
  • That's strange. I don't have such a problem. Can you check out my sample app here: https://github.com/melifaro-/iOSSwiftSample – Igor B. Apr 17 '16 at 07:17
  • Client's code is in the AppDelegate. Does it work for you? – Igor B. Apr 17 '16 at 07:18