Click here to Skip to main content
15,562,561 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to send an empty hashmap from java to C. After that, I need to store data from C to hashmap and again pass it to java. I can now access my java functions from C. But, now I want to pass a hashmap from java and store the data and pass the hashmap back to java. How can I achieve this?
JNIEnv* create_vm(JavaVM** jvm)
    JNIEnv* env;
    JavaVMInitArgs vm_args;
    JavaVMOption options;

    options.optionString = "-Djava.class.path=*";

    vm_args.version = JNI_VERSION_1_8;
    vm_args.nOptions = 1;
    vm_args.options = &options;
    vm_args.ignoreUnrecognized = 0;

    int res = JNI_CreateJavaVM(jvm, (void**)&env, &vm_args); 

    if (res < 0)
        printf("Error code:%d\n", res);
    return env;

int main()
    JNIEnv* env;
    JavaVM* jvm;
    env = create_vm(&jvm);
    if (env == NULL)
        printf("Failed to get env"); 
        return 1;

    jclass cls = (*env)->FindClass(env, "*"); 
    if (cls != NULL)
        printf("Found the class");
        jmethodID jmid = (*env)->GetStaticMethodID(env, cls, "main", "([Ljava/lang/String;)V");
        if (jmid != NULL)
            (*env)->CallStaticVoidMethod(env, cls, jmid, NULL); //Here
            printf("env->CallStaticVoidMethod returned\n"); 

        printf("\nUnable to find the requested class\n");

    return 0;

I need to pass the hashmap there(mentioned above) and store data from C and pass it back to java. How can I achieve this?

What I have tried:

I have tried passing the data as array. But, I need to pass it as Java hashmap now.
Updated 12-May-21 22:16pm
Rick York 13-May-21 2:38am    
I suspect you will have to pass a plain, old array to the C code, have it fill it in, and then write code in java to load the data from the array into the hashmap. That seems to be a cleaner approach to me.
15160877 13-May-21 3:00am    
How do I do that? Can you possibly share any code here for doing that?
Rick York 13-May-21 11:40am    
No, I have none. I have experience with interfacing C with other languages and this kind of thing happens often. Apprently Richard agrees with me.

1 solution

You have to start again from the other side. You need to create a C library with a method that can accept a plain array from Java. The C code can then fill it with the data requested before returning to Java. The JNI documentation shows how to do it.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900