将 jlong​​ 转换为 long 是否安全?

smg*_*smg 2 c++ java-native-interface android android-ndk

我正在使用 C++ 中的 JNI 为 Android 开发本机插件。我想打印一个jlong值,该值定义为 64 位值。将其直接转换为 long 是否安全,或者是否有任何我应该注意的特定于平台的问题?

jlong foo = 2;

// This results in the following warning:
// Format specifier '%ld' requires 'long' argument instead of 'jlong'.
printf("%ld", foo);

// This works without a warning.
printf("%ld", (long)foo);
Run Code Online (Sandbox Code Playgroud)

Dam*_*mon 5

不。是的。

正如您所注意到的,Java 定义long为 64 位数字。C++ 不这样做,long只能保证至少与 一样大int,因此它也可能是一个 32 位数字。

然而,恰好给定组合“Android”+“64 位”,确实long是一个 64 位整数。这与例如 Windows 中它仍然只是一个 32 位整数的情况大不相同。
因此,假设您仅针对 64 位进行编写,您现在可以停止阅读。

但是,为什么要麻烦呢?

C++ 借用了 C 的<cstdint>头文件,其中定义了类型int64_t。所以你需要使用一些你知道是 64 位类型的东西,你担心它可能不适合?

好吧,使用保证可以应对的类型:

#include <cstdio>
using my_jlong = int64_t;
Run Code Online (Sandbox Code Playgroud)