1

我目前正在尝试在 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*。有什么办法可以解决这个问题吗?

4

1 回答 1

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)

另一个观察 - 你不需要将 String 转换为 NSString。Swift 与 Obj-C 的互操作性为您免费提供。

顺便说一句,我使用 Swift 2.2

于 2016-04-16T18:53:24.917 回答