繁体   English   中英

用Objective-C ++包装c ++代码

[英]Wrapping a c++ code with Objective-C++

我目前正在尝试在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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM