Reputation: 212
I am trying to use C++ functions in Swift. To do that, I use an 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 C++ 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 the 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 a couple of times calling this method, it throws an EXC_BAD_ACCESS error.
How can I solve this problem?
Upvotes: 0
Views: 339
Reputation: 30341
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;
}
Upvotes: 1