Using common C ++ / STL code with Objective-C ++

I have a lot of common C ++ code that I would like to use in my iPhone application. I added .cpp and .h files to my Xcode project and used the classes in my Objective-C ++ code. The project compiles with 0 errors or warnings.

However, when I run it in the simulator, I get the following error when I try to access the STL method in my objective-c code (for example .c_str()):

Program received signal:  "EXC_BAD_ACCESS".

Unable to disassemble std::string::c_str.

Here is an example of the code causing the error:

[name setText:[[NSString alloc] initWithCString:myCPlusPlusObject->cppname.c_str()]];

where nameis the NSTextField object and cppnameis the member of std :: string myCPlusPlusObject.

Am I going to do it right? Is there a better way to use STL-loaded C ++ classes in Objective-C ++? I would like, if possible, to support regular C ++ files, to avoid having to maintain the code in two places.

Thanks in advance!

+3
source share
3 answers

Make sure the string is not empty before passing it to the function initWithCString.

Also the function you are using is deprecated, use this option instead .

+3
source

Please note that this line of code:

[name setText:[[NSString alloc] initWithCString:myCPlusPlusObject->cppname.c_str()]];

leak created string.

http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html.

, , , . :

[name setText:[[[NSString alloc] initWithCString:myCPlusPlusObject->cppname.c_str() encoding:NSUTF8StringEncoding] autorelease]];

NSString* myCPlusPlusString = [[NSString alloc] initWithCString:myCPlusPlusObject->cppname.c_str() encoding:NSUTF8StringEncoding];
[name setText:myCPlusPlusString];
[myCPlusPlusString release];

[name setText:[NSString stringWithCString:myCPlusPlusObject->cppname.c_str() encoding:NSUTF8StringEncoding]];

, . - , , iPhone.

, , - "", , stringWithCString . , , , , , , , , , , "alloc" "new" "copy", .

+2

:

if (myCPlusPlusObject)
{
    [name setText:[[NSString alloc] initWithUTF8String:myCPlusPlusObject->cppname.c_str()]];
}
else
{
    [name setText:@"Plop: Bad myCPlusPlusObject"];
}

NULL, , , std::String , , c_str() '\ 0', .

+1

Source: https://habr.com/ru/post/1709825/


All Articles