简体   繁体   中英

Casting from NSString to “const std::string&”

I'm really rusty with my C++ and ObjectiveC, but I have linked a C++ library into my iOS project. I am having trouble calling the method in my C++ library from my iOS App.

Ultimately, I'm having a hard time grokking the type conversion, and getting it right.

Can someone help point out what I am doing wrong, and offer the solution?

// In my C++ Library

std::string Foo::bar(const std::string& src)
{
    //... 
}

// In my iOS Project:

NSString *input = @"Foo";    
NSString *output = [NSString stringWithCString: Foo::bar(std::string([input UTF8String])).c_str() encoding: [NSString defaultCStringEncoding]];

The error I get in Xcode is:

Undefined symbols for architecture x86_64: 
Foo::bar(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)", referenced from...

From what I understand, it's the casting of input which is problemmatic.

I've already scoured StackOverflow, but can't seem to find the specific casting from NSString to const std::string&

Thanks!

To convert from NSString to const std::string& , you just need to use [input UTF8String] . Try my code below

NSString *input = @"Foo";
std::string str = [input UTF8String];
NSString *output = [NSString stringWithUTF8String:Foo::bar(str).c_str()];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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