通过JNI在C和Java之间的指针 [英] Passing pointers between C and Java through JNI

查看:225
本文介绍了通过JNI在C和Java之间的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在这个岗位<随后的@tulskiy的建议通过JNI存储在Java中C指针href=\"http://stackoverflow.com/questions/1632367/passing-pointers-between-c-and-java-through-jni/1634310#1634310\">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 have return (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 to jlong and back is guaranteed to work provided jlong is big enough (which you're implicitly assuming it is anyway).
  • Casting from uinttptr_t to jlong and back avoids a sign-extension, but is undefined behaviour if the uintptr_t is too big to fit in a jlong (but all "sane" architectures/compilers just use two's complement arithmetic)

这篇关于通过JNI在C和Java之间的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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