2016-04-16 69 views
1

我目前正在嘗試使用我在iphone應用程序中用C++編寫的一段代碼。我已閱讀關於使用objective-C++封裝C++代碼。我想調用C++函數使用參數2的std :: string,並返回一個std :: string的:用Objective-C++包裝C++代碼

// 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 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) 
    } 

錯誤的目標-C++函數:無法將NSString類型的值轉換爲預期的參數類型PerformanceObjCtoCPlusPlus。 我認爲我得到的錯誤是因爲我無法將字符串類型的swift轉換爲NSString *。 有沒有解決這個問題的方法?

+1

你試過嗎? http://stackoverflow.com/questions/33118095/cannot-convert-value-of-type-string-to-expected-argument-type-error我不熟悉目標c,但我不認爲runfoo是一個靜態方法 –

回答

0

你,而需要比類的方法來執行對象:

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) 

而且彼此觀察 - 你不需要投字符串的NSString。 Swift與Obj-C的互操作性爲你免費提供。

順便說一句,我用斯威夫特2.2

+0

如果有必要,我可以分享我用於問題分析的示例應用程序。 –

+0

我在let res = obj.runfoo(q +「*」+ z)行有錯誤。錯誤:無法將類型'String'的值轉換爲期望的參數類型'(UnsafePointer ,UnsafePointer )' – Marwan

+0

這很奇怪。我沒有這樣的問題。你能看看我的示例應用程序在這裏:https://github.com/melifaro-/iOSSwiftSample –