简体   繁体   中英

Pass multiple parameters from java to c++ application via JNI

On the java side, when there is a message received, java function

JavaMessageReceived(int msgNo, int msgLen, int[] msgData, long msgTimestamp)

will be called, so the information of the message will be stored in msgNo, msgLen, msgData and msgTimestamp.

Then I would like to pass the value in msgNo, msgLen and msgData, msgTimestamp to a function in c++ side(application), called

CppGotMessage(int *no, int *len, int*data, long* timestamp)

When I call CppGotMessage() I will get the information of the received message.

How do I do this via JNI?(can't use JNA or other third software)
From this link: http://doc-snapshot.qt-project.org/qdoc/qandroidjniobject.html

I noticed the ResigterNatives won't work for me, because when I call CppGotMessage on c++ side, I don't have any arguments to pass to the java function. I just need to got the value from the java function and store them in my CppGotMessage function's parameters..

First you need to declare a native java function:

native JavaMessageNative(int msgNo, int msgLen, int[] msgData, long msgTimestamp);

Then you need to implement this method in the c++ part. Calling javah will create the signature for your native function.

Within this function you first need to convert the java types to native ones. For the integer this is trivial but the int[] you need to use the appropriate JNI function. Search for GetIntArrayElements .

After that you can simply call your own CppGotMessage function.

There are a couple of tools that help using JNI:

  1. JNA uses JNI but you write the custom glue code in Java instead of C++. JNAerator can generate the Java glue code from a .h file. I suggest you write a simplified .h file just the declarations you need to call your function.

  2. SWIG uses JNI but you write an interface definition file (annotated .h) file and don't have to write any glue code. As with using JNAerator, you should minimize the declarations from your .h file.

  3. If you do use JNI yourself, javah will translate the native members of your Java class into a C++ .h file with functions that you implement using the JNI API . javap -s is useful when you need signatures to find Java methods to call through JNI. The book by the JNI designer is very useful, The Java™ Native Interface: Programmer's Guide and Specification .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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