I am trying to use C++ functions in Swift. To do that I use Objective-C wrapper. I am not familiar with Objective-C and C++ so much.
My Wrapper function takes Swift String as a parameter from textField.
And inside of c++ I encrypt the passed string and return it.
Here is my Cpp function:
string StringModifier::encryptString(string str) {
int i;
for(i=0; (i<100 && str[i] != '\n'); i++) {
str[i] = str[i] + 2;
}
return str;
}
And inside of Wrapper
StringModifier stringModifier;
-(NSString*)encryptString:(NSString*)str; {
string strng = [str UTF8String];
string finalString = stringModifier.encryptString(strng);
NSString *result = [NSString stringWithCString: finalString.c_str() encoding:[NSString defaultCStringEncoding]];
return result;
}
The output of encryptString("Helloworld") is "Jgnnqyqtnf¬√√0*?"
and after couple of calling this method throws EXC_BAD_ACCESS error.
How can I solve this problem?
Thanks.
>Solution :
You need to check for the null character (\0) in C++.
Change your for-loop to this:
for(i=0; (i<100 && str[i] != '\n' && str[i] != '\0'); i++) {
str[i] = str[i] + 2;
}
Even better, loop depending on how big the string is:
string StringModifier::encryptString(string str) {
for (int i = 0; i < str.size() && str[i] != '\n'; i++) {
str[i] = str[i] + 2;
}
return str;
}