围绕 C 主函数编写 JNI 包装器 [英] writing a JNI wrapper around a C main function

查看:23
本文介绍了围绕 C 主函数编写 JNI 包装器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须围绕现有的 C 源代码编写 JNI 包装器,以便可以从 Java 调用它们.但是大多数 C 源代码都接受命令行参数(argc 和 argv)并广泛使用它们.有什么方法可以将我在 Java 中捕获的字符串 args[] 传递给 C 函数,而对 C 源文件的更改很少?

I have to write JNI wrappers around existing C source codes so that they can be called from Java. But most of the C source codes take in command line arguments (argc and argv) and use them extensively. Is there any way that I can pass the string args[] that I capture in Java, to the C function with very minimal changes to the C source file?

我相信作为 JNI 包装器的一部分,我必须用 C 语言编写一个由 Java 代码调用的函数.

I believe that as part of the JNI wrappers, I have to write a function in C that is called by the Java code.

推荐答案

当然,您必须编写一个由 Java 代码调用的 C 函数.

For sure, you'll have to write a C function called by the Java code.

从 Radiodef 指向的答案中可以看出,该函数将接收 jobjectarray,因为 java String[]jni 作为 jobjectArray.

As seen in the answer pointed to by Radiodef, that function will receive a jobjectarray, as a java String[] is represented in jni as a jobjectArray.

在函数中,您必须 malloc 一个 C 数组,用于存储旧版 main 函数在其 char **argv 中所期望的所有 char* 指针论据.

In the function, you will have to malloc a C arrays, for storing all the char* pointers that your legacy main function is expecting in it's char **argv argument.

您将在该数组中存储分配的指针,以便能够立即释放 JNI 对象.您可能会避免使用这些 malloc,但代价是将 JNI 资源存储在另一个数组中以供进一步发布,所以我认为这不是一个好主意.

You will store in that array malloced pointers, in order to be able to release the JNI objects immediately. You may avoid those malloc, but at the cost of storing JNI resources in another array for further release, so I don't think it's a goo idea.

请记住,遗留主函数的约定是第一个参数(索引 0)是程序名称".你将不得不伪造它.

Remember that the convention for legacy main functions is that the first arg (index 0) is the 'program name'. You will have to fake it.

void MyJNIFunction(JNIEnv *env, jobject object, jobjectArray stringArray) {

    // Get the number of args
    jsize ArgCount = (*env)->GetArrayLength(env, stringArray);
    // malloc the array of char* to be passed to the legacy main
    char ** argv = malloc(sizeof(char*)*(ArgCount+1)); // +1 for fake program name at index 0
    argv[ 0 ] = "MyProgramName";

    int i;
    for ( i = 0; i < ArgCount; ++i ) {
       jstring string = (jstring)((*env)->GetObjectArrayElement(env, stringArray, i));
       const char *cstring = (*env)->GetStringUTFChars(env, string, 0);
       argv[ i + 1 ] = strdup( cstring );
       (*env)->ReleaseStringUTFChars(env, string, cstring );
       (*env)->DeleteLocalRef(env, string );
    } 

    // call the legacy "main" function
    LegacyMain( ArgCount + 1, argv );

    // cleanup 
    for( i = 0; i < ArgCount; ++i ) free( argv[ i + 1 ] ); 
    free( argv );
    return;
}

这篇关于围绕 C 主函数编写 JNI 包装器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆