简体   繁体   English

JNI:将包装器类型用于原始数据类型以模拟C ++中的指针传递

[英]JNI:Using Wrapper Types for primitive data types to simulate passing by pointers in C++

The problem is the famous parameter passing problem in JNI. 问题是JNI中著名的参数传递问题。

I want to wrap a c++ code that passes primitive parameters by pointer and I just want to confirm one thing, to make sure that the Wrapper classes can not be use for my problem. 我想包装一个通过指针传递原始参数的c ++代码,我只想确认一件事,以确保Wrapper类不能用于我的问题。

As you all know the Wrapper types like Byte(for byte) and Interger(for int) do not support setter method so i can't use them to set the value of a passes object using the setter, 大家都知道,像Byte(for byte)和Interger(for int)之类的包装器类型不支持setter方法,因此我无法使用它们使用setter来设置pass对象的值,

But, what about the assignment operator? 但是,赋值运算符呢?

Is there any way i can call the assignment operator(=) of Wrapper Type "Byte" using JNI in the C++ code? 有什么方法可以在C ++代码中使用JNI调用包装类型“字节”的赋值运算符(=)?

a codeed sample of the idea is as follows: 该想法的编码示例如下:

JNIEXPORT void JNICALL 
Java_InstanceMethodCall_nativeMethod(JNIEnv *env, jobject obj/*A Byte object*/)
{
    jclass cls = (*env)->GetObjectClass(env, obj);
    jmethodID mid = (*env)->GetMethodID(env, cls, "=(or something else you can tell me)", "(B)V");
    if (mid == NULL) {
        return; /* method not found */
    }
    (*env)->CallVoidMethod(env, obj, mid);
}

Yes, you can look up or set the private "value" field of primitive boxes in native code. 是的,您可以在本机代码中查找或设置原始框的私有“值”字段。 However, because the field is private, you're not guaranteed that the field be present in all VM implementations. 但是,由于该字段是私有的,因此不能保证该字段在所有VM实现中都存在。 You're also at the mercy of the interpreter making assumptions about the value being passed in remaining unchanged (similar in concept to changing the contents behind a pointer marked "* const"). 您还受解释器的摆布,他们假设传递的值保持不变(概念上与更改标记为“ * const”的指针后面的内容类似)。

You're better off passing in a primitive array of length one, pinning the array and obtaining the corresponding pointer for use as the "address" of your primitive to be changed. 最好传入一个长度为1的基本数组,固定该数组并获取相应的指针,以用作要更改的基本元素的“地址”。

Here is an instructional example showing how to mutate an immutable object. 这是一个说明性示例,显示了如何更改不可变对象。 You should think hard and long about this and in the end you should not do this. 您应该对此进行认真而漫长的思考,最后您不应该这样做。

native void nativeModifyByte(Byte b);

JNIEXPORT void JNICALL Java_nativeModifyByte(JNIEnv * env, jobject o, jobject b) {
   jclass c = (*env)->GetObjectClass(env, b);
   jfieldID fid = (*env)->GetFieldID(env, c, "value", "B");
   jbyte oldVal = (*env)->GetByteField(env, b, fid);
   (*env)->SetByteField(env, b, fid, 42);
}

Usage: 用法:

    byte v = 13;
    Byte b = new Byte(v);
    nativeModifyByte(b);
    System.out.println(b);

Output: 输出:

    42

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM