I am trying to understand the jni with some examples. I am trying to get the java stack trace using jni and so this is what I was doing
HelloJNI.java
package test.com.jni;
public class HelloJNI {
static {
System.loadLibrary("hello"); // Load native library at runtime
}
private native StackTraceElement[] getStackTraceNative(Throwable throwable);
private native void printStackTraceNative(Throwable throwable);
public static void main(String[] args) {
test();
}
public static void test() {
new HelloJNI().printStackTraceNative(new Throwable()); //Invoke native method
new HelloJNI().getStackTraceNative(new Throwable());
}
}
Native code (keeping the error handling out for simplicity)
test_com_jni_HelloJNI.c
JNIEXPORT jobjectArray JNICALL Java_test_com_jni_HelloJNI_getStackTraceNative (JNIEnv * env, jobject object, jthrowable exception) {
jclass exceptionClazz = (*env)->GetObjectClass(env, exception);
jmethodID getStackTraceMethod = (*env)->GetMethodID(env, exceptionClazz, "getStackTrace", "()[Ljava.lang.StackTraceElement");
jobjectArray stacktraces = (*env)->CallObjectMethod(env, exception, getStackTraceMethod);
return stacktraces;
}
JNIEXPORT void JNICALL Java_test_com_jni_HelloJNI_printStackTraceNative (JNIEnv * env, jobject object, jthrowable exception) {
jclass exceptionClazz = (*env)->GetObjectClass(env, exception); // can't fail
jmethodID printStackTraceMethod = (*env)->GetMethodID(env, exceptionClazz, "printStackTrace", "()V");
(*env)->CallVoidMethod(env, exception, printStackTraceMethod);
}
Now in this code native printStackTraceNative method works and it prints the stack trace however, getStackTraceNative doesn't. When I check the core dump file it says that java has thrown an exception java/lang/NoSuchMethodError for getStackTrace. I am confused because the parameter I am passing to getStackTraceNative method is of the type throwable and throwable should have the method getStackTrace.
What concept I possibly be missing here, any help on this is appreciated. Thanks
You got the method signature wrong. In method signatures the periods in the qualified class name are replaced by forward slashes. The signature for getStackTrace is therefore ()[Ljava/lang/StackTraceElement; (also note the semicolon)
You can get the method signatures from class files with javap with -s option:
javap -classpath '/path/to/jre/lib/rt.jar' -s java.lang.Throwable
Related
I'm trying to test out some JNI code integrating a Java class with some ROS functionality and I'm struggling to get the Java methods linked up correctly. I've got the native code compiled against the JNI interface correctly (or so I think) but at runtime I get an UnsatisifiedLinkError on the first native method I have defined. At this point I'm not sure if the root cause is that the JVM isn't properly loading the .so file (in the same directory, and I've tried -Djava.library.path=.) or if it's successfully loading it and it's not finding the method correctly.
This error message gives so little to go on, is there a way to get more info about what exactly is causing it?
I'm not opposed to posting the source code if it would help, though I'd have to do some editing before I can upload it so I'll wait to see if you guys think it might be helpful.
Talker.java:
public class Talker {
/**
* ROS Native methods
*
* Simple passthrough to the C++ native methods in the ROS layer
*/
private static native void rosAdvertise();
private static native void rosPublish();
private static native void rosSpinOnce();
{
System.loadLibrary("ros-test-native-talker");
}
public static void main(String[] args) {
rosAdvertise();
while (true) {
rosPublish();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
rosSpinOnce();
}
}
}
ros-test-native-talker.cpp:
#include "test_rostest_Talker.h"
#include "ros/ros.h"
#include "std_msgs/Time.h"
ros::Publisher outbound;
JNIEXPORT void JNICALL Java_test_rostest_Talker_rosAdvertise
(JNIEnv *, jclass) {
int argc = 0;
char **argv;
ros::init(argc, argv, "ros-native-timing-tester");
ros::NodeHandle n;
outbound = n.advertise<std_msgs::Time>("chatter", 1000);
}
JNIEXPORT void JNICALL Java_test_rostest_Talker_rosPublish
(JNIEnv *, jclass) {
ros::Time tx_timestamp = ros::Time::now();
ROS_INFO("Sending message at %d.%d", tx_timestamp.sec, tx_timestamp.nsec);
std_msgs::Time msg;
msg.data = tx_timestamp;
outbound.publish(msg);
}
JNIEXPORT void JNICALL Java_test_rostest_Talker_rosSpinOnce
(JNIEnv *, jclass) {
ros::spinOnce();
}
and the output:
rush#lubuntu64vm:~/javarostest$ java -Djava.library.path=. -cp ros-test-native-1.0-SNAPSHOT.jar test.rostest.Talker
Exception in thread "main" java.lang.UnsatisfiedLinkError: test.rostest.Talker.rosAdvertise()V
at test.rostest.Talker.rosAdvertise(Native Method)
at test.rostest.Talker.main(Talker.java:21)
I have no clue why but refactoring the above code slightly caused it to work. If I take the native methods out of the main classand put them in a separate class (thus removing the static modifier on the native methods) which is invoked by the main class, it all links and works fine. I'm not certain nor do I even have a clue why, but I think the static modifier on those methods was causing some issues.
I'm trying to use a python interpreter in my Android app to run SymPy. I already compiled Python for arm using this guide. http://mdqinc.com/blog/2011/09/cross-compiling-python-for-android/
This got me a libpython2.7.so file which I put into jniLibs/armeabi/.
In my app I load it as follows:
public class PythonTest {
static {
System.loadLibrary("python2.7");
}
public static native void Py_Initialize();
public static native void Py_Finalize();
public static native int PyRun_SimpleString(String s);
}
I am trying to use the methods from the headers located in the include directory which can also be found here: https://docs.python.org/2/c-api/
When I run the app on my device I get the following error:
No implementation found for void com.example.dorian.testapplication.PythonTest.Py_Initialize() (tried Java_com_example_dorian_testapplication_PythonTest_Py_1Initialize and Java_com_example_dorian_testapplication_PythonTest_Py_1Initialize__)
So to me this seems like the library loaded but it seems to look for the JNIEXPORT functions. But shouldn't I be able to use this library without writing specific C++ files? And if not, how would I accomplish this. Might there be a tool to generate wrapper files or something similar?
You need a JNI wrapper lib that will serve as a bridge between your Java code and libpython2.7.so. It may be enough for straters to have the three functions wrapped according to the JNI convention, e.g.
JNIEXPORT jint JNICALL com_example_dorian_testapplication_PythonTest_PyRun_1SimpleString
(JNIEnv *env, jclass jc, jstring js)
{
char* cs = env->GetStringUTFChars(js, 0);
std::string s = new std::string(cs);
env->ReleaseStringUTFChars(env, js, cs);
return PyRun_SimpleString(s.c_str());
}
If something is not clear, please read the tutorial at http://joaoventura.net/blog/2014/python-android-2.
Note that you can use any package name for the PythonTest class, not necessarily related to your Android app package name, e.g.
package com.python27;
class Python {
static {
System.loadLibrary("python2.7");
}
public static native void Initialize();
public static native void Finalize();
public static native int Run(String s);
}
will expect the JNI wrappers
JNIEXPORT void JNICALL com_python27_Python_Initialize(JNIEnv *env, jclass jc);
JNIEXPORT void JNICALL com_python27_Python_Finalize(JNIEnv *env, jclass jc);
JNIEXPORT jint JNICALL com_python27_Python_Run(JNIEnv *env, jclass jc, jstring js);
I start JVM from C++ program.
C++ code:
JNIEXPORT jobject JNICALL com_javelin_JavelinMarketData_callBackIntoNative(JNIEnv* env, jobject obj, jlong ptr)
{
std::cout << "com_javelin_JavelinMarketData_callBackIntoNative called" << std::endl;
}
int main()
{
JavaVM* jvm;
JNIEnv* env;
...
JNI_CreateJavaVM(&jvm, (void **)&env, &args);
jmethodID mainMethod = env->GetStaticMethodID(helloWorldClass, "main", "([Ljava/lang/String;)V");
env->CallStaticVoidMethod(helloWorldClass, mainMethod, ...);
}
then I need my C++ function called back from java:
Java code:
native void callBackIntoNative(long ptr);
public void onResponse(long param)
{
System.out.println("Calling callBackIntoNative()");
callBackIntoNative(param);
}
When I run my C++ program, JVM starts correctly, but after it prints "Calling callBackIntoNative()" the following acception appears:
Exception during callBackIntoNative(): 'com.javelin.JavelinMarketData.callBackIntoNative(J)V'
java.lang.UnsatisfiedLinkError: com.javelin.JavelinMarketData.callBackIntoNative(J)V
Can you please help?
Thanks, but I found a solution: I should have registered my C++ function as a native method using the code:
const JNINativeMethod methods[] = { { "callBackIntoNative", "(J)V", (void*)&com_javelin_JavelinMarketData_callBackIntoNative } };
const int methods_size = sizeof(methods) / sizeof(methods[0]);
jclass jClass = env->FindClass("com/javelin/JavelinMarketData");
env->RegisterNatives(jClass, methods, methods_size);
Now it works fine.
I would compile your callback apart into a dynamic library (.dll, .so, whatever your OS) and put it accesible to your java program. Then you just load your library by using JNI and call from your java classes whatever functionality you have in the library.
I have the following problem:
in my java program I'm calling a native function that creates an object of the "MyEventReceiver" class in C++, later in that java program I'm calling an native function that calls the "test" method of that object. In this "test"-method I want to call a method of the java object that I used to call the second native function, but as soon as make this call, the jvm crashes.
This is the native code that creates the MyEventReceiver object:
JNIEXPORT jlong JNICALL Java_irr4jEventReceiver_native_1createEventReceiver
(JNIEnv *env, jobject obj){
MyEventReceiver *rec = new MyEventReceiver(env, obj);
return (long)rec;
}
this is the native code that i use later in the program to call the "test" method in that object:
JNIEXPORT void JNICALL Java_irr4jEventReceiver_native_1testmethode
(JNIEnv *env, jobject obj, jlong ptrrec){
MyEventReceiver *rec = (MyEventReceiver*)ptrrec;
rec->test();
}
and this is the MyEventReceiver class:
class MyEventReceiver : public IEventReceiver
{
public:
JNIEnv *myenv;
jobject receiverobj;
jclass SEventclass;
jobject eventobj;
jmethodID cid;
jclass cevrec;
jmethodID meth2;
public:
void test(){
eventobj = myenv->AllocObject(SEventclass);
eventobj = myenv->NewObject(SEventclass, cid);
myenv->CallVoidMethod(receiverobj,meth2,eventobj); //this is the line that causes the crash
}
MyEventReceiver(JNIEnv *env, jobject obj)
{
this->myenv=env;
receiverobj = env->NewGlobalRef(obj);
SEventclass = myenv->FindClass("SEvent");
cid = myenv->GetMethodID(SEventclass,"<init>", "()V");
cevrec = myenv->FindClass("MyEventReceiver");
meth2 =myenv->GetMethodID(cevrec, "OnEvent", "(LSEvent;)V");
//test();
}
};
if I call the method "test" at the end of the constructor, it works... only if I make the call later out of the java program... I think it has something to do with the jobject "receiverobj"... seems to get invalid after some time but I don't know why
...I stripped the code a bit...deleted some debug code. The "eventobj" I'm creating is fine... I can call other methods of that object, the methodIDs are also fine, just the line:
myenv->CallVoidMethod(receiverobj,meth2,eventobj);
gives me problems and i dont know why :)
crash message is:
#
# A fatal error has been detected by the Java Runtime Environment:
#
# EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x67d594f4, pid=5292, tid=2400
#
# JRE version: 7.0_21-b11
# Java VM: Java HotSpot(TM) Client VM (23.21-b01 mixed mode, sharing windows-x86 )
# Problematic frame:
# V [jvm.dll+0xa94f4]
#
# Failed to write core dump. Minidumps are not enabled by default on client versions of Windows
#
# An error report file with more information is saved as:
# G:\irr4jjava\irr4j\hs_err_pid5292.log
#
# If you would like to submit a bug report, please visit:
# http://bugreport.sun.com/bugreport/crash.jsp
#
EDIT:
Thanks for the help so far. I tried to use global refs and attached thread but I can't get it to work. I'm not sure if I understood the thing with the attached thread...
I modified the first native method to create a global reference to the jobject and pass it to the constructor:
JavaVM *jvm;
JNIEXPORT jlong JNICALL Java_irr4jEventReceiver_native_1createEventReceiver
(JNIEnv *env, jobject obj){
jobject recobj = env->NewGlobalRef(obj);
env->GetJavaVM(&jvm);
MyEventReceiver *rec = new MyEventReceiver(recobj);
return (long)rec;
}
in the class "MyReceiverObject" I try attach the thread but it still crashes:
class MyEventReceiver : public IEventReceiver
{
public:
JNIEnv *myenv;
jobject receiverobj;
jclass SEventclass;
jobject eventobj;
jmethodID cid;
jclass cevrec;
jmethodID meth2;
public:
void test(){
jvm->AttachCurrentThread((void**)&myenv,NULL);
eventobj = myenv->AllocObject(SEventclass); //crash
eventobj = myenv->NewObject(SEventclass, cid);
myenv->CallVoidMethod(receiverobj,meth2,eventobj);
}
MyEventReceiver(jobject obj)
{
jvm->AttachCurrentThread((void**)&myenv,NULL);
receiverobj=obj;
SEventclass = myenv->FindClass("SEvent");
cid = myenv->GetMethodID(SEventclass,"<init>", "()V");
cevrec = myenv->FindClass("MyEventReceiver");
meth2 =myenv->GetMethodID(cevrec, "OnEvent", "(LSEvent;)V");
//test();
}
};
You need to read the chapter in the JNI Specification about global references. The jobject you were passed in your JNI method is only valid for the life of that method. You need to convert it to a GlobalRef, maybe a WeakGlobalRef, before you store it anywhere that is going to outlive the current invocation.
A similar thing applies to the JNIEnv pointer. It's only valid for the duration of the method it is passed to. If you want to use one in a different thread or at a later time you must get a new one via AttachThread().
I found these in open JDK (System.c file)
static JNINativeMethod methods[] = {
{"currentTimeMillis", "()J", (void *)&JVM_CurrentTimeMillis},
{"nanoTime", "()J", (void *)&JVM_NanoTime},
{"arraycopy", "(" OBJ "I" OBJ "II)V", (void *)&JVM_ArrayCopy},
};
#undef OBJ
JNIEXPORT void JNICALL
Java_java_lang_System_registerNatives(JNIEnv *env, jclass cls)
{
(*env)->RegisterNatives(env, cls,
methods, sizeof(methods)/sizeof(methods[0]));
}
but I was not able to find the native implemetations of these functions
currentTimeMillis
nanoTime
arraycopy
Form where can I get the native implementations of these functions ?
Is that available in open JDK?
if found it in
jdk7/hotspot/src/share/vm/prims/jvm.cpp:229
JVM_LEAF(jlong, JVM_CurrentTimeMillis(JNIEnv *env, jclass ignored))
JVMWrapper("JVM_CurrentTimeMillis");
return os::javaTimeMillis();
JVM_END
the real implementation (for linux) is in
/jdk7/hotspot/src/os/linux/vm/os_linux.cpp
the other methods are just below it