I am working on an android project to process images using Opencv.
I wrote an android jni function that should return a vector but I can't figure out how to do that right.
I tried to convert the vector to jobjectArray but it's not working.
Here is the code I'm working on:
jobjectArray
Java_com_grimg_testtt_MainActivity_getQuadrilateral(
JNIEnv *env,
jobject /* this */,
cv::Mat & grayscale,
cv::Mat & output) {
std::vector<std::string> vec;
cv::Mat approxPoly_mask(grayscale.rows, grayscale.cols, CV_8UC1);
approxPoly_mask = cv::Scalar(0);
std::vector<std::vector<cv::Point>> contours;
std::vector<int> indices(contours.size());
std::iota(indices.begin(), indices.end(), 0);
sort(indices.begin(), indices.end(), [&contours](int lhs, int rhs) {
return contours[lhs].size() > contours[rhs].size();
});
/// Find the convex hull object for each contour
std::vector<std::vector<cv::Point>> hull(1);
cv::convexHull(cv::Mat(contours[indices[0]]), hull[0], false);
std::vector<std::vector<cv::Point>> polygon(1);
approxPolyDP(hull[0], polygon[0], 20, true);
drawContours(approxPoly_mask, polygon, 0, cv::Scalar(255));
//imshow("approxPoly_mask", approxPoly_mask);
if (polygon[0].size() >= 4) // we found the 4 corners
{
return(polygon[0]);
}
return(std::vector<cv::Point>());
}
In the last two lines I'm getting this error which is obvious:
Returning 'std::vector<cv::Point> &' from a function returning 'jobjectArray': Types 'jobjectArray' and 'std::vector<cv::Point>' are not compatible.
What can I do to get over this problem?
Edit :
jclass clazz = (*env).FindClass("java/util/ArrayList");
jobjectArray result = (*env).NewObjectArray(polygon[0].size(), clazz, 0);
if (polygon[0].size() >= 4) // we found the 4 corners
{
for (int n=0;n<polygon[0].size();n++)
{
cv::Point point = (cv::Point) static_cast<cv::Point>(polygon[0][n]);
(*env).CallVoidMethod(result, (*env).GetMethodID(clazz, "add", "(java/lang/Object)V"), point);
}
return result;
}
return result;
}
Edit 2 :
jclass ptCls = env->FindClass("java/awt/Point");
jobjectArray result = (*env).NewObjectArray(polygon[0].size(), ptCls, NULL);
if (result == NULL) return NULL;
if (polygon[0].size() >= 4) // we found the 4 corners
{
for (int n=0;n<polygon[0].size();n++)
{
jobject point = (jobject) static_cast<jobject>(polygon[0][n]);
//(*env).CallVoidMethod(result, (*env).GetMethodID(ptCls, "add", "(java/lang/Object)V"), polygon[0][n]);
(*env).SetObjectArrayElement(result, polygon[0].size(), point);
}
return result;
}
return result;
Error
error: cannot cast from type 'std::__ndk1::__vector_base<cv::Point_<int>, std::__ndk1::allocator<cv::Point_<int> > >::value_type' (aka 'cv::Point_<int>') to pointer type 'jobject' (aka '_jobject *')
jobject point = (jobject) static_cast<jobject>(polygon[0][n]);
In the JNI layer you should map native objects to Java objects (Java objects are allocated on the JVM heap).
cv::Point needs to be converted to a Java class and std::vector needs to be converted to jobjectArray.
Use (*env)->NewObjectArray to create jobjectArray like this:
jobjectArray result = (*env)->NewObjectArray(env, size, PointCls, NULL);
if (result == NULL) return NULL;
The PointCls should refer to the Java class that corresponds to your native Point class.
Then iterate over each native cv::Point object, create a Java Point from it, copy the fields, and put it into the array (using (*env)->SetObjectArrayElement).
Then you can return the result array.
For example like this:
std::vector<cv::Point> const& input = polygon[0];
jclass doubleArray = env->FindClass("[D");
if (doubleArray == NULL) return NULL;
jobjectArray result = env->NewObjectArray(input.size(), doubleArray, NULL);
if (result == NULL) return NULL;
for (int i = 0; i < input.size(); ++i) {
jdoubleArray element = env->NewDoubleArray(2);
if (element == NULL)
break;
jdouble buf[2] = { input[i].x, input[i].y };
env->SetDoubleArrayRegion(element, 0, 2, buf);
env->SetObjectArrayElement(result, i, element);
}
return result;
This will return a 2D array double[][], with x, y corresponding to 0, 1 in the second dimension.
I am trying to capture the variable values using JVMTI, when an exception event is generated, i went through the jvmti documentation and found that there are no functions which let me retrieve the values of the fields(variables), how can this be achieved ?
Below is the Agent code:
#include<jni.h>
#include<jvmti.h>
#include<string.h>
#include<stdlib.h>
#include<stdbool.h>
typedef struct {
jvmtiEnv *jvmti;
jrawMonitorID lock;
} GlobalAgentData;
static GlobalAgentData *gdata;
static bool check_jvmti_error(jvmtiEnv *jvmti,jvmtiError errnum,const char *str){
if(errnum != JVMTI_ERROR_NONE){
char *errnum_str;
errnum_str = NULL;
(void)(*jvmti)->GetErrorName(jvmti,errnum,&errnum_str);
printf("ERROR: JVMTI: %d(%s): %s\n", errnum,
(errnum_str==NULL?"Unknown":errnum_str),
(str==NULL?"":str));
return false;
}
return true;
}
static void deallocate(jvmtiEnv *jvmti,void *ptr){
jvmtiError error;
error = (*jvmti)->Deallocate(jvmti,ptr);
check_jvmti_error(jvmti,error,"Cannot deallocate memory");
}
static void allocate(jvmtiEnv *jvmti,jint len){
jvmtiError error;
void *ptr;
error = (*jvmti)->Allocate(jvmti,len,(unsigned char **)&ptr);
check_jvmti_error(jvmti,error,"Cannot allocate memory");
}
JNICALL jint objectCountingCallback(jlong class_tag,jlong size,jlong* tag_ptr,jint length,void* user_data){
int* count = (int*)user_data;
*count+=1;
return JVMTI_VISIT_OBJECTS;
}
JNIEXPORT jint JNICALL Java_Test_countInstances(JNIEnv *env,jclass thisClass,jclass klass){
int count =0 ;
jvmtiError error;
jvmtiHeapCallbacks callbacks;
jvmtiEnv *jvmti;
(void)memset(&callbacks,0,sizeof(callbacks));
callbacks.heap_iteration_callback = &objectCountingCallback;
jvmti = gdata->jvmti;
error = (*jvmti)->IterateThroughHeap(jvmti,0,klass,&callbacks,&count);
// check_jvmti_error(*gdata->jvmti,error,"Unable to iterate through the heap");
return count;
}
static void enter_critical_section(jvmtiEnv *jvmti){
jvmtiError error;
error = (*jvmti)->RawMonitorEnter(jvmti,gdata->lock);
check_jvmti_error(jvmti,error,"Cannot enter with raw monitor");
}
static void exit_critical_section(jvmtiEnv *jvmti){
jvmtiError error;
error = (*jvmti)->RawMonitorExit(jvmti,gdata->lock);
check_jvmti_error(jvmti,error,"Cannot exit with raw monitor");
}
static void JNICALL callbackVMInit(jvmtiEnv *jvmti,JNIEnv *env,jthread thread){
jvmtiError error;
// enter_critical_section(jvmti);{ /* not needed since we are just setting event notifications */
printf("Initializing JVM\n");
error = (*jvmti)->SetEventNotificationMode(jvmti,JVMTI_ENABLE,JVMTI_EVENT_EXCEPTION,(jthread)NULL);
// error = (*jvmti)->SetEventNotificationMode(jvmti,JVMTI_ENABLE,JVMTI_EVENT_METHOD_ENTRY,(jthread)NULL);
check_jvmti_error(jvmti,error,"Cannot set Exception Event notification");
// } exit_critical_section(jvmti);
}
static void callbackMethodEntry(jvmtiEnv *jvmti,JNIEnv *env,jthread thread,jmethodID method){
jvmtiError error;
jvmtiLocalVariableEntry **table_ptr;
jint count,entry_count_ptr;
jobject value_ptr;
int j;
error = (*jvmti)->GetLocalVariableTable(jvmti,method,&entry_count_ptr,table_ptr);
if(check_jvmti_error(jvmti,error,"Cannot Get Local Variable table\n")){
printf("local variable table entry size : %d %s\n",entry_count_ptr,(*table_ptr)[0].name);
}
// for(j=0;j<*entry_count_ptr;j++){
// error = (*jvmti)->GetLocalObject(jvmti,thread,0,(*table_ptr)[j].slot,&value_ptr);
// printf("Field Name:%s\n",(*table_ptr)[j].name);
// }
}
static void JNICALL callbackException(jvmtiEnv *jvmti,JNIEnv *env,jthread thread,jmethodID method,jlocation location,jobject exception,jmethodID catch_method,jlocation catch_location){
jvmtiFrameInfo frames[10];
jint count,entry_count_ptr;
int i,j;
jvmtiError error;
jobject* value_ptr;
char *name,*sig,*gsig;
jclass declaring_class_ptr;
jvmtiLocalVariableEntry *table_ptr;
error = (*jvmti)->GetStackTrace(jvmti,thread,0,10,frames,&count);
if(check_jvmti_error(jvmti,error,"Cannot Get Frame") && count >=1){
char *methodName,*className;
for(i=0;i<count;i++){
error = (*jvmti)->GetMethodName(jvmti, frames[i].method,&methodName,&sig,&gsig);
if(check_jvmti_error(jvmti,error,"Cannot Get method name")){
error = (*jvmti)->GetMethodDeclaringClass(jvmti,frames[i].method,&declaring_class_ptr);
check_jvmti_error(jvmti,error,"Cannot Get method declaring class");
error = (*jvmti)->GetClassSignature(jvmti,declaring_class_ptr,&className,NULL);
check_jvmti_error(jvmti,error,"Cannot get class signature");
// printf("Got Exception in Method: %s at Line: %ld with Signature:%s,%s within Class:%s\n",methodName,frames[i].location,sig,gsig,className);
for(j=0;j<entry_count_ptr;j++){
callbackMethodEntry(jvmti,env,thread,frames[j].method);
error = (*jvmti)->GetLocalObject(jvmti,thread,i,table_ptr[j].slot,value_ptr);// change the value of the slot parameter
printf("Field Name:%s\n",table_ptr[j].name);
}
}
}
}
/* error = (*jvmti)->GetMethodName(jvmti,method,&name,&sig,&gsig);
check_jvmti_error(jvmti,error,"Cannot Get Method name");
printf("Exception in Method: %s%s at line number: %ld\n",name,sig,location);*/
}
JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM *jvm,char *options,void *reserved){
jvmtiEnv *jvmti;
jvmtiCapabilities capabilities;
jvmtiError error;
jint result;
jvmtiEventCallbacks callbacks;
result = (*jvm)->GetEnv(jvm,(void **)&jvmti,JVMTI_VERSION_1);
if(result!=JNI_OK){
printf("Unable to access JVMTI! \n");
}
gdata = (GlobalAgentData*)malloc(sizeof(GlobalAgentData));
gdata->jvmti=jvmti;
(void)memset(&capabilities,0,sizeof(jvmtiCapabilities));
capabilities.can_tag_objects = 1;
capabilities.can_signal_thread=1;
capabilities.can_get_owned_monitor_info=1;
capabilities.can_generate_method_entry_events=1;
capabilities.can_generate_exception_events=1;
capabilities.can_tag_objects=1;
capabilities.can_access_local_variables=1;
error = (*(gdata->jvmti))->AddCapabilities(gdata->jvmti,&capabilities);
check_jvmti_error(gdata->jvmti,error,"Unable to set Capabilities");
(void)memset(&callbacks,0,sizeof(callbacks));
callbacks.VMInit = &callbackVMInit;
callbacks.Exception = &callbackException;
//callbacks.MethodEntry = &callbackMethodEntry;
error = (*(gdata->jvmti))->SetEventCallbacks(gdata->jvmti,&callbacks,(jint)sizeof(callbacks));
check_jvmti_error(gdata->jvmti,error,"Cannot set event callbacks");
error = (*(gdata->jvmti))->SetEventNotificationMode(gdata->jvmti,JVMTI_ENABLE,JVMTI_EVENT_VM_INIT,(jthread)NULL);
check_jvmti_error(gdata->jvmti,error,"Cannot set event notification");
error = (*(gdata->jvmti))->CreateRawMonitor(gdata->jvmti,"agent data",&(gdata->lock));
check_jvmti_error(gdata->jvmti,error,"Cannot create raw monitor");
printf("A message from my custom super agent!!\n");
return JNI_OK;
}
Below is the output :
ERROR: JVMTI: 101(JVMTI_ERROR_ABSENT_INFORMATION): Cannot Get Local Variable table
#
# A fatal error has been detected by the Java Runtime Environment:
#
# SIGSEGV (0xb) at pc=0x00007f3faab0cefa, pid=14869, tid=0x00007f3fad251700
#
# JRE version: Java(TM) SE Runtime Environment (8.0_111-b14) (build 1.8.0_111-b14)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.111-b14 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# C [liblearnAgent.so+0xefa] callbackException+0x277
#
# Core dump written. Default location: /home/kumard/Desktop/core or core.14869
#
# An error report file with more information is saved as:
# /home/kumard/Desktop/hs_err_pid14869.log
#
# If you would like to submit a bug report, please visit:
# http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#
[1] 14869 abort (core dumped) java -agentlib:learnAgent SimpleThread
This is not the complete answer, but it does resolve some of the problems in your agent and prints out the values for basic data types when exception hits. We have resolved problems in the comment chat. So I'm simply posting the code here. Anyone interested in knowing more about it can see the chat. You're most welcome to give your insights on the problem too.
#include <jni.h>
#include <jvmti.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct {
jvmtiEnv *jvmti;
jrawMonitorID lock;
} GlobalAgentData;
static GlobalAgentData *gdata;
static bool check_jvmti_error(jvmtiEnv *jvmti, jvmtiError errnum,
const char *str) {
if (errnum != JVMTI_ERROR_NONE) {
char *errnum_str;
errnum_str = NULL;
(void) (*jvmti)->GetErrorName(jvmti, errnum, &errnum_str);
printf("ERROR: JVMTI: %d(%s): %s\n", errnum,
(errnum_str == NULL ? "Unknown" : errnum_str),
(str == NULL ? "" : str));
return false;
}
return true;
}
static void JNICALL callbackException(jvmtiEnv *jvmti, JNIEnv *env,
jthread thread, jmethodID method, jlocation location, jobject exception,
jmethodID catch_method, jlocation catch_location) {
jvmtiFrameInfo frames[10];
jint count, entry_count_ptr;
int i, j;
jvmtiError error;
char *sig, *gsig;
jclass declaring_class_ptr;
jvmtiLocalVariableEntry *table_ptr;
error = (*jvmti)->GetStackTrace(jvmti, thread, 0, 10, frames, &count);
if (check_jvmti_error(jvmti, error, "Cannot Get Frame") && count >= 1) {
char *methodName, *className;
for (i = 0; i < count; i++) {
error = (*jvmti)->GetMethodName(jvmti, frames[i].method,
&methodName, &sig, &gsig);
if (check_jvmti_error(jvmti, error, "Cannot Get method name")) {
error = (*jvmti)->GetMethodDeclaringClass(jvmti,
frames[i].method, &declaring_class_ptr);
check_jvmti_error(jvmti, error,
"Cannot Get method declaring class");
error = (*jvmti)->GetClassSignature(jvmti, declaring_class_ptr,
&className, NULL);
check_jvmti_error(jvmti, error, "Cannot get class signature");
error = (*jvmti)->GetLocalVariableTable(jvmti, frames[i].method,
&entry_count_ptr, &table_ptr);
check_jvmti_error(jvmti, error,
"Cannot Get Local Variable Table");
printf(
"Got Exception in Method: %s at Line: %ld with Signature:%s,%s within Class:%s\n",
methodName, frames[i].location, sig, gsig, className);
if (strstr(className, "java") == NULL
&& strstr(className, "javax") == NULL
&& strstr(className, "sun") == NULL) {
for (j = 0; j < entry_count_ptr; j++) {
switch (*(table_ptr[j].signature)) {
case 'B': {
jint value_ptr;
error = (*jvmti)->GetLocalInt(jvmti, thread, i,
table_ptr[j].slot, &value_ptr);
check_jvmti_error(jvmti, error,
"Cannot Get Local Variable Byte");
printf("Value of Field %s is %d.\n", table_ptr[j].name, (jbyte)value_ptr);
break;
}
case 'C': {
jint value_ptr;
error = (*jvmti)->GetLocalInt(jvmti, thread, i,
table_ptr[j].slot, &value_ptr);
check_jvmti_error(jvmti, error,
"Cannot Get Local Variable Char");
printf("Value of Field %s is %c.\n", table_ptr[j].name, (jchar)value_ptr);
break;
}
case 'D': {
jdouble value_ptr;
error = (*jvmti)->GetLocalDouble(jvmti, thread, i,
table_ptr[j].slot, &value_ptr);
check_jvmti_error(jvmti, error,
"Cannot Get Local Variable Double");
printf("Value of Field %s is %f.\n", table_ptr[j].name, value_ptr);
break;
}
case 'F': {
jfloat value_ptr;
error = (*jvmti)->GetLocalFloat(jvmti, thread, i,
table_ptr[j].slot, &value_ptr);
check_jvmti_error(jvmti, error,
"Cannot Get Local Variable Float");
printf("Value of Field %s is %f.\n", table_ptr[j].name, value_ptr);
break;
}
case 'I': {
jint value_ptr;
error = (*jvmti)->GetLocalInt(jvmti, thread, i,
table_ptr[j].slot, &value_ptr);
check_jvmti_error(jvmti, error,
"Cannot Get Local Variable Integer");
printf("Value of Field %s is %d.\n", table_ptr[j].name, value_ptr);
break;
}
case 'J': {
jlong value_ptr;
error = (*jvmti)->GetLocalLong(jvmti, thread, i,
table_ptr[j].slot, &value_ptr);
check_jvmti_error(jvmti, error,
"Cannot Get Local Variable Long");
printf("Value of Field %s is %ld.\n", table_ptr[j].name, value_ptr);
break;
}
case 'S':{
jint value_ptr;
error = (*jvmti)->GetLocalInt(jvmti, thread, i,
table_ptr[j].slot, &value_ptr);
check_jvmti_error(jvmti, error,
"Cannot Get Local Variable Short");
printf("Value of Field %s is %d.\n", table_ptr[j].name, (jshort)value_ptr);
break;
}
case 'Z':{
jint value_ptr;
error = (*jvmti)->GetLocalInt(jvmti, thread, i,
table_ptr[j].slot, &value_ptr);
check_jvmti_error(jvmti, error,
"Cannot Get Local Variable Boolean");
printf("Value of Field %s is %d.\n", table_ptr[j].name, (jboolean)value_ptr);
break;
}
case 'L':{
jobject value_ptr;
error = (*jvmti)->GetLocalObject(jvmti, thread, i,
table_ptr[j].slot, &value_ptr);
check_jvmti_error(jvmti, error,
"Cannot Get Local Variable Object");
printf("Value of Field %s is .\n", table_ptr[j].name);
break;
}
default:
printf("Can't get %s type.\n",
table_ptr[j].signature);
}
printf("Field Signature:%s\n", table_ptr[j].signature);
}
}
}
}
}
}
JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM *jvm, char *options, void *reserved) {
jvmtiEnv *jvmti;
jvmtiCapabilities capabilities;
jvmtiError error;
jint result;
jvmtiEventCallbacks callbacks;
result = (*jvm)->GetEnv(jvm, (void **) &jvmti, JVMTI_VERSION_1);
if (result != JNI_OK) {
printf("Unable to access JVMTI! \n");
}
gdata = (GlobalAgentData*) malloc(sizeof(GlobalAgentData));
gdata->jvmti = jvmti;
(void) memset(&capabilities, 0, sizeof(jvmtiCapabilities));
capabilities.can_generate_exception_events = 1;
capabilities.can_access_local_variables = 1;
error = (*(gdata->jvmti))->AddCapabilities(gdata->jvmti, &capabilities);
check_jvmti_error(gdata->jvmti, error, "Unable to set Capabilities");
error = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE,
JVMTI_EVENT_EXCEPTION, (jthread) NULL);
check_jvmti_error(jvmti, error, "Cannot set Exception Event notification");
(void) memset(&callbacks, 0, sizeof(callbacks));
callbacks.Exception = &callbackException;
error = (*(gdata->jvmti))->SetEventCallbacks(gdata->jvmti, &callbacks,
(jint) sizeof(callbacks));
check_jvmti_error(gdata->jvmti, error, "Cannot set event callbacks");
error = (*(gdata->jvmti))->CreateRawMonitor(gdata->jvmti, "agent data",
&(gdata->lock));
check_jvmti_error(gdata->jvmti, error, "Cannot create raw monitor");
printf("A message from my custom super agent!!\n");
return JNI_OK;
}
I'm using QtCreator to deploy C++/Java applications on Android. But I think my problem may not be specific to the way QtCreator deploys the app.
I want to create a C++ library providing a specific functionnality. To do so, the library needs to instantiate a Java class, this last one will be used to do some SDK functions class (for stuff that are not available in the NDK/C++ API).
Creating and using java objects from a C++ program works fine. I package the .java file to the application environment during compilation/deployment and then I can use the Java class via two approachs:
Declare JNI_OnLoad, load class id, method id, and later call them using jni
Use Qt QAndroidJniObject objects (this is specific to QtCreator)
Now the problem comes when I want to create and use java objects from a C++ library. It only works if the .java file is packaged with the top-level application. I could not find a way to package the java with and only with the library itself. Meaning that anyone why needs to use my library will not only have to simply link with the library, but will also need to package the .java file(s) needed by my library. This breaks encapsulation and gives a hard time to the end developer writing programs and simply wanting to load a library and expecting it to embed all it needs to work on its own...
My question is: How can the library embed the java file, so that this java file does not need to be part of the top level program package to let the library use it?
Here is a quick sample: MainWindow constrctor calls 4 functions themselves trying to create and use Java objects. Only the first two calls work...
main.cpp:
#include <QApplication>
#include <QMainWindow>
#include "MyLib.h"
#include <QtAndroidExtras/QAndroidJniObject>
#include "jni.h"
#include <assert.h>
// load java classes from main program
JavaVM* s_javaVM = NULL;
jclass s_classID = 0;
jmethodID s_ctorMethodID = 0;
jmethodID s_callmethodID = 0;
bool loadJava( JNIEnv *env )
{
jclass clazz = env->FindClass("my/FooPrg");
if (!clazz)
{
qCritical("Can't find FooPrg class");
return false;
}
// keep a global reference to it
s_classID = (jclass)env->NewGlobalRef(clazz);
// search for its contructor
s_ctorMethodID = env->GetMethodID(s_classID, "<init>", "()V");
if (!s_ctorMethodID )
{
qCritical("Can't find class contructor");
return false;
}
// search for a method
s_callmethodID = env->GetMethodID(s_classID, "Mult", "(I)I");
if (!s_callmethodID )
{
qCritical("Can't find Mult method");
return false;
}
return true;
}
jint JNICALL JNI_OnLoad(JavaVM *vm, void *)
{
s_javaVM = vm;
JNIEnv* env = NULL;
if (s_javaVM->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_4) != JNI_OK)
return -1;
loadJava( env );
return JNI_VERSION_1_4;
}
void callJavaFunctionFromPrgWithQt()
{
if ( QAndroidJniObject::isClassAvailable("my/FooPrg") )
{
QAndroidJniObject obj("my/FooPrg","()V");
if ( obj.isValid() )
{
jint res = obj.callMethod<jint>("Mult", "(I)I", 0x0002);
assert( res == 4 );
}
else
{
assert( false );
}
}
else
{
assert( false );
}
}
void callJavaFunctionFromPrgWithJniLoad()
{
if ( s_classID != 0 && s_ctorMethodID != 0 && s_callmethodID != 0 )
{
JNIEnv* env = NULL;
if (s_javaVM->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_4) != JNI_OK)
assert(false);
jobject j_object = env->NewGlobalRef( env->NewObject(s_classID, s_ctorMethodID ) );
jint res = env->CallIntMethod(j_object, s_callmethodID, 0x0002 );
assert( res == 4 );
}
else
{
assert( false );
}
}
class MainWindow : public QMainWindow
{
public:
MainWindow()
{
callJavaFunctionFromPrgWithQt(); // works
callJavaFunctionFromPrgWithJniLoad(); // works
callJavaFunctionFromLibWithQt(); // fails, assert
callJavaFunctionFromLibWithJniLoad(); // fails, because libraries JNI_OnLoad can't find FooLib.java!
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
MyLib.h:
#pragma once
void callJavaFunctionFromLibWithQt();
void callJavaFunctionFromLibWithJniLoad();
MyLib.cpp:
#include "MyLib.h"
#include <QtAndroidExtras/QAndroidJniObject>
#include "jni.h"
#include <assert.h>
// load java classes from main program
JavaVM* s_javaVM = NULL;
jclass s_classID = 0;
jmethodID s_ctorMethodID = 0;
jmethodID s_callmethodID = 0;
bool loadJava( JNIEnv *env )
{
jclass clazz = env->FindClass("my/FooLib");
if (!clazz)
{
qDebug("Can't find FooLib class");
return false;
}
// keep a global reference to it
s_classID = (jclass)env->NewGlobalRef(clazz);
// search for its contructor
s_ctorMethodID = env->GetMethodID(s_classID, "<init>", "()V");
if (!s_ctorMethodID )
{
qDebug("Can't find class contructor");
return false;
}
// search for a method
s_callmethodID = env->GetMethodID(s_classID, "Mult", "(I)I");
if (!s_callmethodID )
{
qDebug("Can't find Mult method");
return false;
}
return true;
}
jint JNICALL JNI_OnLoad(JavaVM *vm, void *)
{
s_javaVM = vm;
JNIEnv* env = NULL;
if (s_javaVM->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_4) != JNI_OK)
return -1;
// uncommenting this makes the application crash upon load....
//loadJava( env );
return JNI_VERSION_1_4;
}
void callJavaFunctionFromLibWithQt()
{
if ( QAndroidJniObject::isClassAvailable("my/FooLib") )
{
QAndroidJniObject obj("my/FooLib","()V");
if ( obj.isValid() )
{
jint res = obj.callMethod<jint>("Mult", "(I)I", 0x0002);
assert( res == 4 );
}
else
{
assert( false );
}
}
else
{
assert( false ); // this assertion is reached!
}
}
void callJavaFunctionFromLibWithJniLoad()
{
if ( s_classID != 0 && s_ctorMethodID != 0 && s_callmethodID != 0 )
{
JNIEnv* env = NULL;
if (s_javaVM->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_4) != JNI_OK)
assert(false);
jobject j_object = env->NewGlobalRef( env->NewObject(s_classID, s_ctorMethodID ) );
jint res = env->CallIntMethod(j_object, s_callmethodID, 0x0002 );
assert( res == 4 );
}
else
{
assert( false ); // this assertion is reached!
}
}
FooPrg.java:
package my;
import java.lang.Integer;
public class FooPrg
{
public FooPrg()
{
}
public int Mult(int val)
{
return val * 2;
}
}
FooLib.java:
package my;
import java.lang.Integer;
public class FooLib
{
public FooLib()
{
}
public int Mult(int val)
{
return val * 2;
}
}
jniload.pro:
TARGET = jniload
CONFIG += qt resources
QT += core gui widgets
android: QT += androidextras
SOURCES += src/main.cpp
TEMPLATE = app
INCLUDEPATH += ifc
LIBS += \
-l$$OUT_PWD/../../lib/jniload_lib/libjniload_lib.so
ANDROID_EXTRA_LIBS += \
$$OUT_PWD/../../lib/jniload_lib/libjniload_lib.so
ANDROID_PACKAGE_SOURCE_DIR = data/android/root
OTHER_FILES += data/android/root/src/my/FooPrg.java
jniload_lib.pro:
TARGET = jniload_lib
CONFIG += qt resources
QT += core gui widgets
android: QT += androidextras
SOURCES += src/MyLib.cpp
HEADERS += ifc/MyLib.h
TEMPLATE = lib
INCLUDEPATH += ifc
# This does has apparently no effect on library
ANDROID_PACKAGE_SOURCE_DIR = data/android/root
OTHER_FILES += data/android/root/src/my/FooLib.java
Finaly got a way to work this out.
I removed ANDROID_PACKAGE_SOURCE_DIR line from jniload.pro file and hanlde manual copy of the .java files through custom build steps:
custom_jniload_lib_step.target = jniload_lib_mockup.h
custom_jniload_lib_step.commands = $(COPY_DIR) data\android\root ..\..\android-build
QMAKE_EXTRA_TARGETS += custom_jniload_lib_step
PRE_TARGETDEPS += jniload_lib_mockup.h
custom_jniload_step.target = jniload_mockup.h
custom_jniload_step.commands = $(COPY_DIR) data\android\root ..\..\android-build
QMAKE_EXTRA_TARGETS += custom_jniload_step
PRE_TARGETDEPS += jniload_mockup.h
Then, upon deployment, android-build/src contains both FooLib.java and FooPrg.java and then both library and program can access them!
Okay, I'm all out of ideas on this one. Does anyone have any idea how I can hook into Java's exception pipeline in order to catch (and log to a text file) all exceptions that are occurring?
The situation is this: I have a library in a JAR file (A) which in turn depends on a second JAR file (B). A has no main class, as it's simply a class library, which I'm accessing and invoking through the JNI. The problem I'm having is this. When I attempt to initialise the JNI with A loaded, the JNI returns an unspecified error.
I strongly suspect that this error originates from an instantiation of Log4J's logger unit, which is occurring in static code (outside of a method) in B, which I believe is throwing an IOException as a result of permissions problems on the log file. I'm having issues finding out what's going on, however, as the exception (which I suspect is the cause of the problem) is being thrown during the linking stage (when A imports B) and so cannot be caught by a try-catch block. Also, since there is no main method there is no obvious place to put a try-catch block in order to catch this exception.
I would like some way of catching all exceptions that arise in either JAR and dumping them into a text file. I cannot (easily) modify B (I do not have the decompiled JAR). Any ideas?
Here is the C code which invokes the JNI with the specified libraries and options:
_DLL_EXPORT PyObject *initVM(PyObject *self, PyObject *args, PyObject *kwds)
{
static char *kwnames[] = {
"classpath", "initialheap", "maxheap", "maxstack",
"vmargs", NULL
};
char *classpath = NULL;
char *initialheap = NULL, *maxheap = NULL, *maxstack = NULL;
char *vmargs = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|zzzzz", kwnames,
&classpath,
&initialheap, &maxheap, &maxstack,
&vmargs))
return NULL;
if (env->vm)
{
PyObject *module_cp = NULL;
if (initialheap || maxheap || maxstack || vmargs)
{
PyErr_SetString(PyExc_ValueError,
"JVM is already running, options are ineffective");
return NULL;
}
if (classpath == NULL && self != NULL)
{
module_cp = PyObject_GetAttrString(self, "CLASSPATH");
if (module_cp != NULL)
classpath = PyString_AsString(module_cp);
}
if (classpath && classpath[0])
env->setClassPath(classpath);
Py_XDECREF(module_cp);
return getVMEnv(self);
}
else
{
JavaVMInitArgs vm_args;
JavaVMOption vm_options[32];
JNIEnv *vm_env;
JavaVM *vm;
unsigned int nOptions = 0;
PyObject *module_cp = NULL;
vm_args.version = JNI_VERSION_1_4;
JNI_GetDefaultJavaVMInitArgs(&vm_args);
if (classpath == NULL && self != NULL)
{
module_cp = PyObject_GetAttrString(self, "CLASSPATH");
if (module_cp != NULL)
classpath = PyString_AsString(module_cp);
}
#ifdef _jcc_lib
PyObject *jcc = PyImport_ImportModule("jcc");
PyObject *cp = PyObject_GetAttrString(jcc, "CLASSPATH");
if (classpath)
add_paths("-Djava.class.path=", PyString_AsString(cp), classpath,
&vm_options[nOptions++]);
else
add_option("-Djava.class.path=", PyString_AsString(cp),
&vm_options[nOptions++]);
Py_DECREF(cp);
Py_DECREF(jcc);
#else
if (classpath)
add_option("-Djava.class.path=", classpath,
&vm_options[nOptions++]);
#endif
Py_XDECREF(module_cp);
if (initialheap)
add_option("-Xms", initialheap, &vm_options[nOptions++]);
if (maxheap)
add_option("-Xmx", maxheap, &vm_options[nOptions++]);
if (maxstack)
add_option("-Xss", maxstack, &vm_options[nOptions++]);
if (vmargs)
{
#ifdef _MSC_VER
char *buf = _strdup(vmargs);
#else
char *buf = strdup(vmargs);
#endif
char *sep = ",";
char *option;
for (option = strtok(buf, sep); option; option = strtok(NULL, sep))
{
if (nOptions < sizeof(vm_options) / sizeof(JavaVMOption))
add_option("", option, &vm_options[nOptions++]);
else
{
free(buf);
for (unsigned int i = 0; i < nOptions; i++)
delete vm_options[i].optionString;
PyErr_Format(PyExc_ValueError, "Too many options (> %d)",
nOptions);
return NULL;
}
}
free(buf);
}
//vm_options[nOptions++].optionString = "-verbose:gc";
//vm_options[nOptions++].optionString = "-Xcheck:jni";
vm_args.nOptions = nOptions;
vm_args.ignoreUnrecognized = JNI_FALSE;
vm_args.options = vm_options;
if (JNI_CreateJavaVM(&vm, (void **) &vm_env, &vm_args) < 0)
{
for (unsigned int i = 0; i < nOptions; i++)
delete vm_options[i].optionString;
PyErr_Format(PyExc_ValueError,
"An error occurred while creating Java VM");
return NULL;
}
env->set_vm(vm, vm_env);
for (unsigned int i = 0; i < nOptions; i++)
delete vm_options[i].optionString;
t_jccenv *jccenv = (t_jccenv *) PY_TYPE(JCCEnv).tp_alloc(&PY_TYPE(JCCEnv), 0);
jccenv->env = env;
#ifdef _jcc_lib
registerNatives(vm_env);
#endif
return (PyObject *) jccenv;
}
}
Okay, so I've got the solution I was after. The solution is an update to the following segment of the code listed in the question:
if (JNI_CreateJavaVM(&vm, (void **) &vm_env, &vm_args) < 0)
{
for (unsigned int i = 0; i < nOptions; i++)
delete vm_options[i].optionString;
PyErr_Format(PyExc_ValueError,
"An error occurred while creating Java VM");
return NULL;
}
The adaptation supports the construction of a more detailed error message which adds two specific pieces of information:
The error code (if any) which is returned by the JNI_CreateJavaVM method;
The detailed Java exception which occurs in the event that such an error code arises.
The above snippet from the original code was replaced with the following:
vmInitSuccess = JNI_CreateJavaVM(&vm, (void **) &vm_env, &vm_args);
if (vmInitSuccess < 0)
{
for (unsigned int i = 0; i < nOptions; i++)
delete vm_options[i].optionString;
//Set up basic error message
sprintf(strVMInitSuccess, "%d", vmInitSuccess);
strcpy(strVMError, "An error occurred while creating Java VM (No Exception): ");
strcat(strVMError, strVMInitSuccess);
//Get exception if there is one
if((exc = vm_env->ExceptionOccurred()))
{
//Clear the exception since we have it now
vm_env->ExceptionClear();
//Get the getMessage() method
if ((java_class = vm_env->FindClass ("java/lang/Throwable")))
{
if ((method = vm_env->GetMethodID(java_class, "getMessage", "()Ljava/lang/String;")))
{
int size;
strExc = static_cast<jstring>(vm_env->CallObjectMethod(exc, method));
charExc = vm_env->GetStringUTFChars(strExc, NULL);
size = sizeof(strVMError) + sizeof(charExc);
char strVMException[size];
strcpy(strVMException, "An error occurred while creating Java VM (Exception): ");
strcat(strVMException, charExc);
PyErr_Format(PyExc_ValueError, strVMException);
return NULL;
}
}
}
PyErr_Format(PyExc_ValueError, strVMError);
return NULL;
}
Thanks to #Parsifal for help with this solution.