3

I am writing a C module with jni for android.
my java class is

public class Payment {
    private static Payment payment = null;
    private long nativeObj;
    private byte[] sendBuffer;
    private byte[] recvBuffer;
    private byte[] msg;

    private Payment() {
        this.sendBuffer = new byte[1024];
        this.recvBuffer = new byte[1024];
        this.msg = new byte[1024];
    }

    public native void setArray();

 }

i want to fill byte arrays of Payment instance in c and i can not do it.
what is the procedure of jni call for this purpose?

i get the field id of sendBuffer with

jclass thisClass = (*env)->GetObjectClass(env, obj);
jfieldID sendId = (*env)->GetFieldID(env, thisClass, "sendBuffer", "[B");

but i can not figure out how to copy data from char[1024] to sendBuffer.

1 Answer 1

3

You can use something like this to copy data from C to java bytes array;

jint_Java_com_stack_overflow_copyBytes(JNIEnv *e, jclass obj, jlong p)
{
    jclass thisClass = (*env)->GetObjectClass(e, obj);
    jfieldID sendId = (*env)->GetFieldID(e, thisClass, "sendBuffer", "[B");        
    jbyteArray bytes = (*e)->GetObjectField(e, obj, sendId)

    jbyte* b = (*e)->GetByteArrayElements(e, bytes, NULL);
    memcpy(myCBytes, b, len);
    (*e)->ReleaseByteArrayElements(e, bytes, b, 0);
}
Sign up to request clarification or add additional context in comments.

3 Comments

i don't want to pass my instance attribute (byte[]) to native function!
@COP you can use jbyteArray bytes = (*e)->GetObjectField(e, obj, sendId) to access the jbyteArray if you want.
@cleblanc It is sometimes best to refactor data copying and conversion operations from JNI code to Java code. Often, in such cases, the native methods would become private (and possibly static), being bridges to JNI rather than part of the class's public interface.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.