2020-05-06 18:03:37 +08:00
|
|
|
//
|
|
|
|
// Created by DXL on 2017/9/1.
|
|
|
|
//
|
|
|
|
|
|
|
|
//including header
|
|
|
|
#include <malloc.h>
|
|
|
|
#include <jni_tools.h>
|
|
|
|
#include "stdbool.h"
|
|
|
|
|
2020-05-07 16:57:15 +08:00
|
|
|
// native thread attach label
|
2020-05-06 18:03:37 +08:00
|
|
|
static bool g_IsAttach;
|
|
|
|
|
2020-05-07 16:57:15 +08:00
|
|
|
// get current env for jvm
|
2020-05-06 18:03:37 +08:00
|
|
|
JNIEnv *getJniEnv() {
|
|
|
|
JNIEnv *currentThreadEnv;
|
|
|
|
g_IsAttach = false;
|
|
|
|
if ((*g_JavaVM)->GetEnv(g_JavaVM, (void **) ¤tThreadEnv, JNI_VERSION_1_4) != JNI_OK) {
|
|
|
|
LOGE("Get Env Fail!");
|
|
|
|
if ((*g_JavaVM)->AttachCurrentThread(g_JavaVM, ¤tThreadEnv, NULL) != JNI_OK) {
|
|
|
|
LOGE("Attach the current thread Fail!");
|
|
|
|
g_IsAttach = false;
|
|
|
|
return NULL;
|
|
|
|
} else {
|
|
|
|
g_IsAttach = true;
|
|
|
|
LOGE("Attach the current thread Success!");
|
|
|
|
return currentThreadEnv;
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
g_IsAttach = false;
|
|
|
|
//LOGE("Get Env Success!");
|
|
|
|
return currentThreadEnv;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-07 16:57:15 +08:00
|
|
|
// detach native thread from jvm
|
|
|
|
void detachThread() {
|
2020-05-06 18:03:37 +08:00
|
|
|
if (g_IsAttach) {
|
|
|
|
(*g_JavaVM)->DetachCurrentThread(g_JavaVM);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-07 16:57:15 +08:00
|
|
|
// cmd arg parse
|
2020-05-06 18:03:37 +08:00
|
|
|
CMD *parse_command_line(const char *commandStr) {
|
|
|
|
CMD *cmd = (CMD *) malloc(sizeof(CMD));
|
|
|
|
if (!cmd) {
|
|
|
|
return NULL;
|
|
|
|
}
|
2020-05-07 16:57:15 +08:00
|
|
|
// copy the source to the heap
|
2020-05-06 18:03:37 +08:00
|
|
|
char *pTmp = strdup(commandStr);
|
2020-05-07 16:57:15 +08:00
|
|
|
// new memory size is default 20 for char **
|
2020-05-06 18:03:37 +08:00
|
|
|
int size = 20;
|
|
|
|
cmd->cmd = (char **) malloc(size * sizeof(char **));
|
2020-05-14 05:30:42 +08:00
|
|
|
if (!cmd->cmd) {
|
|
|
|
free(cmd);
|
|
|
|
return NULL;
|
|
|
|
}
|
2020-05-07 16:57:15 +08:00
|
|
|
// parse
|
2020-05-06 18:03:37 +08:00
|
|
|
char *pStr = strtok(pTmp, " ");
|
|
|
|
cmd->cmd[0] = pStr;
|
|
|
|
int count = 1;
|
|
|
|
for (; pStr != NULL; ++count) {
|
2020-05-07 16:57:15 +08:00
|
|
|
// Capacity expansion
|
2020-05-06 18:03:37 +08:00
|
|
|
if (count == (size - 1)) {
|
|
|
|
size += 20;
|
|
|
|
cmd->cmd = (char **) realloc(cmd->cmd, size * sizeof(char **));
|
|
|
|
}
|
|
|
|
pStr = strtok(NULL, " ");
|
|
|
|
if (pStr) {
|
|
|
|
cmd->cmd[count] = pStr;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
cmd->len = (count - 1);
|
|
|
|
return cmd;
|
|
|
|
}
|
|
|
|
|
2020-05-07 16:57:15 +08:00
|
|
|
// cmd arg struct free
|
2020-05-06 18:03:37 +08:00
|
|
|
void free_command_line(CMD *cmd) {
|
|
|
|
free(cmd->cmd[0]);
|
|
|
|
free(cmd->cmd);
|
|
|
|
free(cmd);
|
2020-05-06 19:38:51 +08:00
|
|
|
}
|