简体   繁体   English

使用SWIG的Java和C ++中的奇怪字符串行为

[英]Strange string behavior in Java and C++ using SWIG

So I'm calling some C++ code from some Java code, using SWIG. 因此,我正在使用SWIG从某些Java代码中调用一些C ++代码。 The function I'm calling takes a string and an integer. 我正在调用的函数需要一个字符串和一个整数。 The problem is, the string seems to change between the two languages: 问题是,字符串似乎在两种语言之间发生了变化:

Java: Java:

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

C++: C ++:

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

And my output from Java is: 我的Java输出是:

GIF89a�Z��

and my output from C++ is: 我的C ++输出是:

GIF89a��Z����

What gives? 是什么赋予了? How do I make the two strings the same? 如何使两个字符串相同?

EDIT: Solved by using Base-64 encoding of the byte array. 编辑:使用字节数组的Base-64编码解决。 Still using SWIG with String in Java and string in C++. 仍在Java中将SWIG与String一起使用,而在C ++中将String与SWIG一起使用。

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. 在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. 使用C ++,您将不会遇到此问题,因为C ++中的string没有字符编码,并且在读写时不应用任何转换,但是您还会遇到另一个问题,因为数据可能包含以NUL字符结尾的字符串。

In java you should use a byte array to hold binary data. 在Java中,您应该使用字节数组来保存二进制数据。 In C++ you would probably use a char pointer to dynamically allocated memory. 在C ++中,您可能会使用char指针来动态分配内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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