【问题标题】:how to convert a NSArray<NSString*> to std::vector<std::string> and pass it to a c++ function in Obejctive-C?如何将 NSArray<NSString*> 转换为 std::vector<std::string> 并将其传递给 Obejctive-C 中的 c++ 函数?
【发布时间】:2020-11-04 08:38:39
【问题描述】:

我是 Objective C 和 C++ 的新手,我已经在 this tutorial 之后在 Objective C 中成功调用了一个 C++ 函数。

但是,上面教程中的示例函数没有输入参数,它是这样的:

//In example C++ file:
std::string Greeting::greet() {
    return someString;
}

//In example Objective-C file:
NSString* newTitle = [NSString stringWithCString:greeting.greet().c_str() encoding:[NSString defaultCStringEncoding]];

就我而言,我有一个 C++ 函数,例如:

std::string Greeting::newGreet(std::vector<std::string> s) {
    // do something
    // f(s)
    return someString;
}

Objective-C 中没有 std::vector<:string>,所以我需要将 NSArray 转换为 std::vector<:string>。

如何进行这种转换,并将其传递给newGreet() 函数?

【问题讨论】:

  • Objective-C++中有std::vector&lt;std::string&gt;

标签: c++ objective-c nsstring nsarray


【解决方案1】:

取决于你想要一个字符串向量还是字符串指针向量:

std::vector<std::string> vect = {};
for (NSString * str in nsArrayOfStrings) {
   std::string cppStr([str UTF8String]);
   vect.push_back(cppStr);
}

或者

std::vector<std::string *> vect = {};
for (NSString * str in nsArrayOfStrings) {
   std::string * cppStrPtr = new std::string([str UTF8String]);
   vect.push_back(cppStrPtr);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-21
    • 1970-01-01
    • 2011-12-21
    • 2011-04-02
    相关资源
    最近更新 更多