gpt4 book ai didi

java - 将指针从 C 传递到 Java 变为 NULL

转载 作者:太空宇宙 更新时间:2023-11-03 11:38:30 25 4
gpt4 key购买 nike

我正在开发一个适用于 x86 的 Android 应用程序,它需要与 C 进行一些集成。我一直在使用 swig/JNI 来完成这项工作,并且大部分情况下运行顺利。但是,指针一直给我一些错误。

我的问题是,我能够在模拟器 (ARM) 中成功引用变量地址,但在设备 (x86) 上,事情并不顺利。

使用 this link 中的示例,我发现一旦该地址传递给 Java,C 中任何已分配变量的地址都会变为 NULL。例如……

Swig 生成的 JNI:

SWIGEXPORT jlong JNICALL Java_exampleJNI_new_1intp(JNIEnv *jenv, jclass jcls) {
jlong jresult = 0 ;
int *result = 0 ;
(void)jenv;
(void)jcls;
result = (int *)new_intp();
LOGI("Result is %x", result);
*(int **)&jresult = result;
LOGI("JResult is %x", jresult);
return jresult;
}

包含 new_intp() 的源文件:

static int *new_intp() {
return (int *) calloc(1,sizeof(int));
}

我有打印语句检查地址的值,因为它源自 C 并传递给 Java。在 new_intp() 中,新变量被分配了一个好看的地址,但是一旦这个值返回到 JNI 并被转换为 jlong​​,它就会变成 NULL。

换句话说,*(int **)&jresult = result;导致 jresult 为 0。

为什么会这样? x86 是否有一些特殊性不允许 JNI 使用指针?还是因为我是在物理设备而不是模拟器上测试它?

问候

最佳答案

实际上,这是一个pointer-aliasing问题。 SWIG 使用老式的 C 指针技术,当优化开启时,这些技术在较新的 GCC 中不起作用。专门埋在 SWIG 文档中 says what to do :

Important

If you are going to use optimisations turned on with gcc (for example -O2), ensure you also compile with -fno-strict-aliasing. The GCC optimisations have become more aggressive from gcc-4.0 onwards and will result in code that fails with strict aliasing optimisations turned on. See the C/C++ to Java typemaps section for more details.

关于java - 将指针从 C 传递到 Java 变为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6753241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com