Закрытие / очистка JNI-соединений - PullRequest
1 голос
/ 28 ноября 2011

Кто-нибудь знает, есть ли способ остановить / сбросить соединение между приложением Java и его источником C ++, связанным с Jni ...?

Я попытался сбросить объект, вызвав его конструктор, но он не работает ...

MyJniJavaClass jni = новый MyJniJavaClass ();

---- МОИ ДЕЙСТВИЯ ----

jni = new MyJniJavaClass ();

---- ДРУГИЕ ДЕЙСТВИЯ ----

На самом деле моя проблема в том, что я пытаюсь получить доступ к своей C ++ DLL два раза. Это работает хорошо в первый раз, а затем вылетает второй ... Я попытался получить доступ к C ++ DLL, используя два разных экземпляра объекта, но он все еще вылетает

Итак, я полагаю, что проблема связана с тем фактом, что DLL-библиотека C ++ остается открытой в памяти моего приложения и что мне не нравится, когда я обращаюсь к ней дважды («одновременно») ...

Вот код C ++:

////////////////// ADDED
#include "stdafx.h" 

#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <math.h>
#include <XtremeAPI.h> 
////////////////// ADDED

#include "MainFrame_Jni_Functions.h"
#include <vector>
#include <string>
#include <iostream>

using namespace std;

// parameters table columns and row number
vector<char*>   paramName;
vector<char*>   paramType;
jdouble*        paramValue;
jdouble*        paramMin;
jdouble*        paramMax;
jdouble*        paramRef;
jint            paramNbRows;

// responses table columns and row number
vector<char*>   respName;
jint            respNbRows;

// objectives table columns and row number
vector<char*>   objName;
vector<char*>   objType;
jint            objNbRows;

// constraints table columns and row number
vector<char*>   conName;
vector<char*>   conType;
jdouble*        conLimit;
jdouble*        conExponent;
jdouble*        conRefVal;
jdouble*        conWeight;
jint            conNbRows;

// interval constraints table columns and row number
vector<char*>   intConName;
vector<char*>   intConType;
jdouble*        intConLowLimit;
jdouble*        intConUpLimit;
jdouble*        intConExponent;
jdouble*        intConWeight;
jint            intConNbRows;

// Xtreme data's
//static XtremeDataGA       xtremeDataGA;
/*XtremeDataFastGA  xtremeDataFastGA;
XtremeDataMGA       xtremeDataMGa;
XtremeDataFastGA    xtremeDataFastGA;
XtremeDataFastMGA   xtremeDataFastMGA;*/


JNIEXPORT void JNICALL Java_MainFrame_Jni_Functions_sendParamToNative
(   JNIEnv *env, jobject jobj, jobjectArray jparamName, jdoubleArray jparamValue, 
jdoubleArray jparamMin, jdoubleArray jparamMax, jdoubleArray jparamRef, jobjectArray jparamType){

    paramNbRows = env->GetArrayLength( jparamName );

    paramValue  = env->GetDoubleArrayElements(jparamValue, 0);
    paramMin    = env->GetDoubleArrayElements(jparamMin, 0);
    paramMax    = env->GetDoubleArrayElements(jparamMax, 0);
    paramRef    = env->GetDoubleArrayElements(jparamRef, 0);

    paramName   = vector<char*>(paramNbRows);
    for(int i=0; i<paramNbRows; i++){ 
        paramName.at(i) =  (char*)env->GetStringUTFChars(
            (jstring)env->GetObjectArrayElement( jparamName, i), 0 );
    }

    paramType   = vector<char*>(paramNbRows);
    for(int i=0; i<paramNbRows; i++){ 
        paramType.at(i) =  (char*)env->GetStringUTFChars(
            (jstring)env->GetObjectArrayElement( jparamType, i), 0 );
    }

    env->ReleaseDoubleArrayElements(jparamValue,paramValue, 0);
    env->ReleaseDoubleArrayElements(jparamMin,  paramMin,   0);
    env->ReleaseDoubleArrayElements(jparamMax,  paramMax,   0);
    env->ReleaseDoubleArrayElements(jparamRef,  paramRef,   0);
}

JNIEXPORT void JNICALL Java_MainFrame_Jni_Functions_sendRespToNative    (JNIEnv *env, jobject jobj, jobjectArray jRespName){        

respNbRows  = env->GetArrayLength( jRespName );

respName    = vector<char*>(respNbRows);
for(int i=0; i<respNbRows; i++){ 
    respName.at(i) =  (char*)env->GetStringUTFChars(
        (jstring)env->GetObjectArrayElement( jRespName, i), 0 );
}
}

JNIEXPORT void JNICALL Java_MainFrame_Jni_Functions_sendObjToNative  
(JNIEnv *env, jobject jobj, jobjectArray jObjName, jobjectArray jObjType){

objNbRows   = env->GetArrayLength( jObjName );

objName     = vector<char*>(objNbRows);
for(int i=0; i<objNbRows; i++){ 
    objName.at(i) =  (char*)env->GetStringUTFChars(
        (jstring)env->GetObjectArrayElement( jObjName, i), 0 );
}

objType     = vector<char*>(objNbRows);
for(int i=0; i<objNbRows; i++){ 
    objType.at(i) =  (char*)env->GetStringUTFChars(
        (jstring)env->GetObjectArrayElement( jObjType, i), 0 );
}
}

JNIEXPORT void JNICALL Java_MainFrame_Jni_Functions_sendConToNative
(   JNIEnv *env, jobject jobj, jobjectArray jConName, jobjectArray jConType, 
    jdoubleArray jConLimit, jdoubleArray jConExpo, jdoubleArray jConRefVal, jdoubleArray jConWeight){

        conNbRows       = env->GetArrayLength( jConName );

        conLimit        = env->GetDoubleArrayElements(jConLimit, 0);
        conExponent     = env->GetDoubleArrayElements(jConExpo, 0);
        conRefVal       = env->GetDoubleArrayElements(jConRefVal, 0);
        conWeight       = env->GetDoubleArrayElements(jConWeight, 0);

        conName         = vector<char*>(conNbRows);
        for(int i=0; i<conNbRows; i++){ 
            conName.at(i) =  (char*)env->GetStringUTFChars(
                (jstring)env->GetObjectArrayElement( jConName, i), 0 );
        }

        conType         = vector<char*>(conNbRows);
        for(int i=0; i<conNbRows; i++){ 
            conType.at(i) =  (char*)env->GetStringUTFChars(
                (jstring)env->GetObjectArrayElement( jConType, i), 0 );
        }

        env->ReleaseDoubleArrayElements(jConLimit,  conLimit,   0);
        env->ReleaseDoubleArrayElements(jConExpo,   conExponent,0);
        env->ReleaseDoubleArrayElements(jConRefVal, conRefVal,  0);
        env->ReleaseDoubleArrayElements(jConWeight, conWeight,  0);
}

JNIEXPORT void JNICALL Java_MainFrame_Jni_Functions_sendIntConToNative
(   JNIEnv *env, jobject jobj, jobjectArray jIntConName, jobjectArray jIntConType, 
    jdoubleArray jIntConLowLimit, jdoubleArray jIntConUpLimit, jdoubleArray jIntConExp, jdoubleArray jIntConWeight){

        intConNbRows = env->GetArrayLength( jIntConName );

        intConLowLimit  = env->GetDoubleArrayElements(jIntConLowLimit, 0);
        intConUpLimit   = env->GetDoubleArrayElements(jIntConUpLimit, 0);
        intConExponent  = env->GetDoubleArrayElements(jIntConExp, 0);
        intConWeight    = env->GetDoubleArrayElements(jIntConWeight, 0);

        intConName = vector<char*>(intConNbRows);
        for(int i=0; i<intConNbRows; i++){ 
            intConName.at(i) =  (char*)env->GetStringUTFChars(
                (jstring)env->GetObjectArrayElement( jIntConName, i), 0 );
        }

        intConType = vector<char*>(intConNbRows);
        for(int i=0; i<intConNbRows; i++){ 
            intConType.at(i) =  (char*)env->GetStringUTFChars(
                (jstring)env->GetObjectArrayElement( jIntConType, i), 0 );
        }

        env->ReleaseDoubleArrayElements(jIntConLowLimit,intConLowLimit, 0);
        env->ReleaseDoubleArrayElements(jIntConUpLimit, intConUpLimit,  0);
        env->ReleaseDoubleArrayElements(jIntConExp,     intConExponent, 0);
        env->ReleaseDoubleArrayElements(jIntConWeight,  intConWeight,   0);
}

JNIEXPORT void JNICALL Java_MainFrame_Jni_Functions_printTables  (JNIEnv *env, jobject jobj){

cout    << endl << "Printing from XtremeAPIProject" << endl;

cout    << endl << "paramTable" << endl;
for(int i=0; i<paramNbRows; i++)
    cout    << "line " << i << " : "    
                << " name=" << paramName.at(i)  
                << " val="  << paramValue[i]    
                << " min="  << paramMin[i] 
                << " max="  << paramMax[i]      
                << " ref="  << paramRef[i]
                << " type=" << paramType.at(i)          
            << endl;

cout    <<endl << "respTable" << endl;
for(int i=0; i<respNbRows; i++)
    cout    << "line " << i << " : "    
                << " name=" << respName.at(i)       
            << endl;

cout    <<endl << "objTable" << endl;
for(int i=0; i<objNbRows; i++)
    cout    << "line " << i << " : "    
                << " name=" << objName.at(i)        
                << " type=" << objType.at(i)    
            << endl;


cout    <<endl << "conTable" << endl;
for(int i=0; i<conNbRows; i++)
    cout    << "line " << i << " : "    
                << " name=" << conName.at(i)    
                << " type=" << conType.at(i)
                << " limit="<< conLimit[i] 
                << " exp="  << conExponent[i]       
                << " refV=" << conRefVal[i]
                << " wght=" << conWeight[i]         
            << endl;


cout    <<endl << "intConTable" << endl;
for(int i=0; i<intConNbRows; i++)
    cout    << "line " << i << " : "    
                << " name=" << intConName.at(i) 
                << " type=" << intConType.at(i)
                << " lowL=" << intConLowLimit[i] 
                << " uprL=" << intConUpLimit[i]     
                << " exp="  << intConExponent[i]
                << " wght=" << intConWeight[i]          
            << endl;

cout << endl << "-----------------------------------------------------------------------------" << endl;

return;
}

///////////////////////////////////////// test functions
// Test function
void rosenbrockFunction (std::vector<double>& parameterVector, std::vector<double>& responseVector)
{
double r = 0;

for (unsigned int i=0; i<parameterVector.size (); i++)
    if ( (i+1)%2 == 1 )
        r = r + pow(1.0E+00 - parameterVector.at (i), 2.0);
    else
        r = r + 100.0E+00 * 
        pow(parameterVector.at (i) - pow(parameterVector.at (i-1), 2.0), 2.0);

responseVector.at (0) = r;
}

// Test function
void zdt1Function (std::vector<double>& parameterVector, std::vector<double>& responseVector)
{
double nDouble = parameterVector.size ();

double f1 = parameterVector.at (0);
double g = 0.0;
for (unsigned int i=1; i<parameterVector.size (); i++)
    g += parameterVector.at (i);
g = 9.0 * g / (nDouble - 1.0);
g += 1.0;
double h = 1.0 - sqrt (f1 / g);

responseVector.at (0) = f1;
responseVector.at (0) = g * h;
}
////////////////////////////////////////////////////////


JNIEXPORT void JNICALL Java_MainFrame_Jni_Functions_runTestGA  (JNIEnv *env, jobject jobj){

//testGA();

//xtremeDataGA = XtremeDataGA();
XtremeDataGA xtremeData = XtremeDataGA();

//--------------- [ Parameters ] ----------------------------------------------------
xtremeData.parameters.resize (2); //paramNbRows

for(int i=0; i<2; i++){ //paramNbRows

    xtremeData.parameters.at(i).name        = paramName.at(i);
    xtremeData.parameters.at(i).valueMin    = paramMin[i];
    xtremeData.parameters.at(i).valueMax    = paramMax[i];
    xtremeData.parameters.at(i).valueRef    = paramRef[i];

    if      (!strcmp(paramType.at(i), "Double"))    
        xtremeData.parameters.at(i).valueType = 3;
    else if (!strcmp(paramType.at(i), "Integer"))
        xtremeData.parameters.at(i).valueType = 2;
    else if (!strcmp(paramType.at(i), "Boolean"))
        xtremeData.parameters.at(i).valueType = 1;
    else
        xtremeData.parameters.at(i).valueType = 0;
}

//--------------- [ Responses ] -----------------------------------------------------
xtremeData.responses.resize (1);

xtremeData.responses.at(0).name   = "F1";

//--------------- [ External simulation ] -------------------------------------------
xtremeData.externalSimulation.externalSimulationType    = 1;
xtremeData.externalSimulation.functionPointer           = &rosenbrockFunction;

//--------------- [ Objective function ] --------------------------------------------
xtremeData.penalties.resize (1);
xtremeData.penalties.at(0).quantityName = "F1";
xtremeData.penalties.at(0).penaltyType  = "MINIMIZE";
xtremeData.penalties.at(0).weight       = 1.0;

//--------------- [ Optimizer ] -----------------------------------------------------
xtremeData.optimizationData.initialSolutionStrategy = 0;
xtremeData.optimizationData.randomSeedStrategy      = 0;

xtremeData.optimizationGAData.reproductionCount = 50;
xtremeData.optimizationGAData.individualCount   = 50;

xtremeData.optimizationGAData.evaluationStrategy.first  = 1;
xtremeData.optimizationGAData.evaluationStrategy.second = 1;
xtremeData.optimizationGAData.GAType                    = 1; // our advance GA

xtremeData.optimizationData.solutionHistoryStrategy = 1;

bool success = XtremeAPIGA (xtremeData);

cout << endl << "success=" << success << endl;


cout << "nb1=" << xtremeData.resultsData.parameter.size() << endl;
cout << "nb2=" << xtremeData.resultsData.parameter.at(0).size() << endl;
cout << "nb3=" << xtremeData.resultsData.parameter.at(0).at(0).size() << endl;

/////////////////////////////////////////////////////////////////////////////////

cout << "begin!!!!!!!!!!!!!!" << endl;

cout << "before!!!!!!!!!!!!!!" << endl;
jclass jclazz = env->FindClass("MainFrame/Jni/TablesObjects");
cout << "after***************" << jclazz <<endl;


int iterationsSize = xtremeData.resultsData.parameter.size();
jdouble* jdbl = new jdouble(iterationsSize);
for(int i=0; i<iterationsSize; i++)
    jdbl[i] = xtremeData.resultsData.parameter.at(i).at(0).at(0);
jdoubleArray jdblArr = env->NewDoubleArray(iterationsSize);
env->SetDoubleArrayRegion(jdblArr, 0, iterationsSize, jdbl);


jclass jStringClass   = env->FindClass("java/lang/String"); 
jobjectArray jStringArray = env->NewObjectArray(6, jStringClass, 0);
for(int i=0; i<6; i++)
    env->SetObjectArrayElement(jStringArray, i, env->NewStringUTF("a") );


jmethodID mid = env->GetStaticMethodID(jclazz, "resultsParameterInsertCol", "([Ljava/lang/Object;[D)V");
env->CallStaticVoidMethod(jclazz, mid, jStringArray, jdblArr);

cout << "end!!!!!!!!!!!!!!" << endl;
}


JNIEXPORT void JNICALL Java_MainFrame_Jni_Functions_destroyAll  (JNIEnv *env, jobject jobj){

// parameters table columns and row number
paramName;
paramType;
paramValue = NULL;
paramMin = NULL;
paramMax = NULL;
paramRef = NULL;
paramNbRows;

// responses table columns and row number
respName;
respNbRows = NULL;

// objectives table columns and row number
objName;
objType;
objNbRows = NULL;

// constraints table columns and row number
conName;
conType;
conLimit = NULL;
conExponent = NULL;
conRefVal = NULL;
conWeight = NULL;
conNbRows = NULL;

// interval constraints table columns and row number
intConName;
intConType;
intConLowLimit = NULL;
intConUpLimit = NULL;
intConExponent = NULL;
intConWeight = NULL;
intConNbRows = NULL;
}

1 Ответ

0 голосов
/ 28 ноября 2011

Все нативные библиотеки загружаются в статическую карту вашего ClassLoader, поэтому вы не можете просто перезагрузить нативную библиотеку в одной JVM. Как разобраться с этим, вы можете посмотреть на интерфейс DLL, он должен содержать что-то вроде метода destroy, destroyN, чтобы библиотека могла сама завершать свои ресурсы.

...