java 将变量从 jBoolean 类型转换为 bool
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6326712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Type casting a variable from jBoolean to bool
提问by Balanivash
When using JNI to interface between Java and C, javah parses a boolean value in Java to jBoolean
in the JNI header file. When I use bool
in the C file, the Visual studio compiler throws a warning that
当使用 JNI 在 Java 和 C 之间进行接口时,javah 将 JavajBoolean
中的布尔值解析到JNI 头文件中。当我bool
在 C 文件中使用时,Visual Studio 编译器会抛出一个警告
warning C4800: 'jboolean' : forcing value to bool 'true' or 'false' (performance warning)
警告 C4800:“jboolean”:强制将值设为布尔值“true”或“false”(性能警告)
Is there any other data type that should be used? Or if bool
is the only data type here, what exactly are the performance problems that I might face?
还有其他数据类型应该使用吗?或者如果bool
是这里唯一的数据类型,我可能面临的性能问题究竟是什么?
采纳答案by Ernest Friedman-Hill
The "performance problem" is that the cast isn't completely free. Casting to bool
essentially means forcing all non-zero values to 1
, which takes a tiny bit of code, as opposed to a "free" cast like widening char
to int
. The "performance problem" is a few extra machine instructions. If you're doing this a million times in a tight loop, OK, maybe you care -- otherwise, no, you shouldn't care at all. This is IMO a silly compiler warning; that small added cost is simply part of the compromise you make when using bool
and the compiler shouldn't be bothering you about it.
“性能问题”是演员不是完全免费的。bool
强制转换为本质上意味着强制所有非零值到1
,这需要一点代码,而不是像扩展char
到的“免费”转换int
。“性能问题”是一些额外的机器指令。如果你在一个紧凑的循环中这样做一百万次,好吧,也许你关心——否则,不,你根本不应该关心。这是 IMO 一个愚蠢的编译器警告;增加的小成本只是您在使用时做出的妥协的一部分,bool
编译器不应该为此打扰您。
回答by Mike Kwan
Try casting to BOOL instead. You might find this thread interesting too: Difference between bool and BOOL.
尝试转换为 BOOL。您可能会发现这个线程也很有趣:bool 和 BOOL 之间的区别。
I'm not quite sure this is what you are looking for however. BOOL is 16 bits, not 8 bits. If that is okay then it is closer to what you're looking for than bool. Otherwise you could use byte. Note if you do end up casting to any of these you won't be able to do == trueanymore. This is also explained in the link I provided.
但是,我不太确定这是否是您要查找的内容。BOOL 是 16 位,而不是 8 位。如果没问题,那么它比 bool 更接近您要查找的内容。否则你可以使用字节。请注意,如果您最终强制转换为这些中的任何一个,您将无法再执行== true了。这也在我提供的链接中进行了解释。