Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting string from C++ to Swift

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading