将jlong​​转换为long是否安全? [英] Is it safe to cast jlong to long?

查看:542
本文介绍了将jlong​​转换为long是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C ++开发带有JNI的Android本机插件.我想打印出一个jlong值,它是

I'm developing a native plugin for Android with JNI in C++. I want to print out a jlong value, which is defined as a 64-bit value. Is it safe to cast it directly to a long, or are there any platform-specific issues I should be aware of?

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);

推荐答案

否.是的.

正如您已经正确注意到的那样,

Java将long定义为64位数字. C ++不会保证long仅与int一样大,因此它可能也是32位数字.

No. Yes.

Java, as you have correctly noticed, defines long as a 64 bit number. C++ does not do that long is only guaranteed to be at least as large as int, so it might as well be a 32-bit number.

但是,发生这种情况是因为给定了组合"Android" +"64位",实际上long是64位整数.这与例如Windows仍然只是32位整数.
因此,假设您只为64位编写,则可以停止此处和现在的阅读.

However, it so happens that given the combination "Android" + "64 bit", indeed long is a 64-bit integer. That's much different from e.g. Windows where it's still just a 32-bit integer.
So, assuming you are writing for 64-bit only, you could stop reading here and now.

C ++从C借用<cstdint>标头,C标头定义了类型int64_t.因此,您需要使用一些已知的64位类型,并且担心它可能不合适?

C++ borrows the <cstdint> header from C, which defines among others the type int64_t. So you need to use something of which you know is a 64-bit type and you're worried it might not fit?

好吧,请使用保证的类型来解决此问题:

Well, use a type that is guaranteed to cope with that:

#include <cstdio>
using my_jlong = int64_t;

这篇关于将jlong​​转换为long是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆