我目前正在尝试在iPhone应用程序中使用用C ++编写的一段代码。我已经阅读了有关使用Objective-C ++包装C ++代码的信息。我尝试调用的C ++函数接受参数2 std :: string并返回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
我正在从Swift调用Objective-C ++函数
// 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)
}
错误:无法将NSString类型的值转换为预期的参数类型PerformanceObjCtoCPlusPlus。我认为我得到的错误是因为我无法将swift的String类型转换为NSString *。有什么解决方法可以解决此问题?
您宁愿执行对象,也不愿执行类方法:
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)
另一个发现-您不需要将String强制转换为NSString。Swift与Obj-C的互操作性可免费为您完成。
顺便说一句,我用的是Swift 2.2
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句