简体   繁体   English

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

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

I am currently trying to use a piece of code I have written in c++ in an iphone application. 我目前正在尝试在iphone应用程序中使用我用c ++编写的一段代码。 I have read about wrapping C++ code using objective-C++. 我已经阅读了使用Objective-C ++包装C ++代码的内容。 the c++ function I am trying to call takes for arguments 2 std::string and returns a std::string: 我试图调用的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

I am calling the objective-C++ function from swift 我从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)
    }

error:Cannot convert value of type NSString to expected argument type PerformanceObjCtoCPlusPlus. 错误:无法将NSString类型的值转换为预期的参数类型PerformanceObjCtoCPlusPlus。 I think the error I am getting is because I cannot convert the String type of swift to a NSString*. 我认为我得到的错误是因为我无法将swift的String类型转换为NSString *。 is there any work-around to solve this problem? 有没有解决这个问题的解决办法?

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. 另一个观察 - 你不需要将String转换为NSString。 Swift's interoperability with Obj-C does it for you for free. Swift与Obj-C的互操作性为您免费提供。

BTW, I use Swift 2.2 顺便说一句,我使用Swift 2.2

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

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