简体   繁体   中英

Strange string behavior in Java and C++ using SWIG

So I'm calling some C++ code from some Java code, using SWIG. The function I'm calling takes a string and an integer. The problem is, the string seems to change between the two languages:

Java:

byte[] bytes = getBytesFromSomewhere();
String rv = new String(bytes, "ASCII");
logger.info(rv.substring(0,30));
f(rv, 10);

C++:

bool f(const string& data, const int num) {
  LOG(ERROR) << "Got string: " << data.substr(0,30);
}

And my output from Java is:

GIF89a�Z��

and my output from C++ is:

GIF89a��Z����

What gives? How do I make the two strings the same?

EDIT: Solved by using Base-64 encoding of the byte array. Still using SWIG with String in Java and string in C++.

What you are reading is a binary file; it doesn't make sense to try to convert the data into a text string in Java. With C++ you won't have this problem because string in C++ does not have a character encoding, and no conversion is applied when reading and writing, but you'll have another problem because the data may contain the string terminating NUL character.

In java you should use a byte array to hold binary data. In C++ you would probably use a char pointer to dynamically allocated memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM