Answer the question
In order to leave comments, you need to log in
Permanently saving a pointer to char* from QString, how?
In general, there was nothing to do in the evening, and one respected one wanted to connect JNI to the project.
But it wasn’t there, it turns out that the JVM takes a special structure with options as input, in which the string is a pointer to the string (char * ).. Without thinking for a long time, I convert the whole thing to char* like this.
JavaVMOption options[alength];
foreach(QString param, jargs)
{
static int i = 0;
QByteArray arr = param.toLocal8Bit();
char * pbuff = arr.data();
options[i].optionString = pbuff;
i++;
}
typedef struct JavaVMOption {
char *optionString;
void *extraInfo;
} JavaVMOption;
typedef struct JavaVMInitArgs {
jint version;
jint nOptions;
JavaVMOption *options;
jboolean ignoreUnrecognized;
} JavaVMInitArgs;
/**
* Метод запуска виртуальной среды java.
* @brief Jvm::launchJVM
*/
bool Jvm::launchJVM()
{
jint alength = (jint)jargs.length();
__debug_p("Args lenght" << alength);
if(alength < 1)
{
__DEBUG_P("No java options");
return false;
}
__DEBUG_P("Launching Java VM...");
JavaVMOption options[alength];
foreach(QString param, jargs)
{
static int i = 0;
//options[i].optionString = param.toLatin1().data();
QByteArray arr = param.toLocal8Bit();
char * pbuff = arr.data();
options[i].optionString = pbuff;
//options[i].optionString = const_cast<char*>(param.toStdString().c_str());
i++;
}
for(int i = 0; i < alength; i++)
{
qDebug() << "%$$%$%$%POINTER IN STRUCT" << options[i].optionString << endl;
}
JavaVMInitArgs vm_args;
jint ret = JNI_GetDefaultJavaVMInitArgs(&vm_args);
if(ret == JNI_ERR)
__debug_p("Error while loading default jvm init args");
vm_args.version = JNI_VERSION_1_6;
vm_args.options = options;
vm_args.nOptions = alength;
vm_args.ignoreUnrecognized = JNI_FALSE;
jint code = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
if(code == JNI_ERR)
{
__DEBUG_P("JVM is not runned, error code" << code);
return false;
}
__DEBUG_P("JVM runned successful");
emit JavaVMRunned(env);
return true;
}
Answer the question
In order to leave comments, you need to log in
Of course it gets lost. You have arr local to the loop body. As soon as the next iteration ends, the resulting pointer becomes invalid.
Make sure the memory referenced by the pointer is not freed until the JVM is done with it.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question