SqliteConnection::htmlTest()
is returning a pointer to a local variable that goes out of scope so it is no longer valid. You could return a `std::string instead and extract the data in the calling function or use some other method to make sure the data hangs around until you use it.
String Mysteriously disappears bringing string from C++ to Obj C++
-
21-09-2022 - |
Question
I'm sure it's something simple, but I can't seem to figure it out. I am basically trying to use c++ to produce an HTML string and to return it to be stored in an objective c model class to be used later in a web view.
The c++ side of it seems to run fine. here's the method that's called in a cpp file:
const char *SqliteConnection::htmlTest(){
HtmlItemValueTableBuilder htmlBuilder = HtmlItemValueTableBuilder();
std::string s = htmlBuilder.test();
cout << "TEST RESULT: " <<s;
return s.c_str();
}
The cout produces the following output (which is what I want):
TEST RESULT: <!doctype html><html><head></head><div><STYLE type="text/css"> body { margin: 10%; } table { border-spacing: 5px; } td { background-color: #EFEFEF; font-size: 20px; padding: 4px; padding-left: 4px; padding-right: 4px; } tr { margin-bottom: 10px; margin-top: 10px; } </STYLE><table><thead></thead><tbody>
<tr><td>hello</td><td>world</td></tr>
</tbody></table></div></html>
The below is the code the calls it in a separate Objective c++ (.mm) file:
-(NSString *)getFieldsMapAsHtmlForResult:(Result *)result {
const char *s = _sqliteConnection->htmlTest();
NSLog(@"Before Conversion: %s", s);
NSString *htmlString = [NSString stringWithUTF8String:s];
NSLog(@"After Conversion: %@",htmlString);
return htmlString;
}
I have seen a lot of people recommend using stringWithUTF8String to convert a c string to an NString. This has worked for me in the past but for some reason, in both the NSLog outputs, I get nothing returned. The string just mysteriously disappears.
Could you recommend what might be causing this?
----- UPDATE ---- Following Retired Ninja's Advice, I tried to make sure that the pointer referenced wasn't to a variable that fell out of scope. I had a Result model c++ class that I was passing on to my obj c++ code successfully. I decided to add a data member, fields_map_as_html, and have the function pass to that instead of to my obj-C++ code.
Solution