问题描述
我一直在这个岗位Passing通过JNI C和Java之间的指针
I've been storing c pointers in Java through JNI by following the advice of @tulskiy in this post Passing pointers between C and Java through JNI
关键是要投的指针作为jlong。因此,从三我有收益率(jlong)PTR;
The trick is to cast the pointer as a jlong. So from c I have return (jlong) ptr;
我返回jlong(总是64位),因为我希望我的code到两个64位和32位系统上运行。在64位计算机上的64位指针的存储器的大小为64,它遵循一个32位的计算机上,在存储器中的指针的大小是32位。
I'm returning a jlong (always 64 bits) because I want my code to work on both 64 and 32 bit systems. The size in memory of a 64 bit pointer on a 64 bit computer is 64 and it follows that on a 32-bit computer, the size of the pointer in memory is 32 bits.
问题是32位机器上,我得到一个编译器警告说:来自不同大小的指针转换为整数。该警告消失,如果我有收益率(jlong)(int32_t)PTR;
然而,这code是不好的64位机
The problem is that on the 32 bit machine I get a compiler warning saying "casting to integer from pointer of different size." The warnings goes away if I havereturn (jlong) (int32_t) ptr;
However this code is not good for the 64 bit machine.
我想有我的code编译没有警告,所以,如果有一个合法的警告,我会看到它。任何人有什么想法?
I would like to have my code compile without warnings so that if there is a legitimate warning I will see it. Anyone have any ideas?
谢谢,
本
推荐答案
有在各种C.方便的整数类型你想要的可能是使用intptr_t和uintptr_t形式:
There are various handy integer types in C. The one you want is probably intptr_t or uintptr_t:
return (jlong)(intptr_t) ptr;
的区别?
- 从
使用intptr_t
铸造到jlong
和背部是保证工作提供了jlong
足够大(这你隐含假设它反正)。 - 从
uinttptr_t
铸造到jlong
和背部避免了符号扩展,但未定义的行为,如果uintptr_t形式
太大,以适应在jlong
- Casting from
intptr_t
tojlong
and back is guaranteed to work providedjlong
is big enough (which you're implicitly assuming it is anyway). - Casting from
uinttptr_t
tojlong
and back avoids a sign-extension, but is undefined behaviour if theuintptr_t
is too big to fit in ajlong
(but all "sane" architectures/compilers just use two's complement arithmetic)
这篇关于通过JNI在C和Java之间的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!