Search code examples
cjava-native-interface

Implementation of C in JNI , syntax changing


One thing that confused me from JNI tutorial website is the changing of C syntax. Do I have to rewrite this

/* helloworld without JNI implementation */

  #include <stdio.h>

  void main()
  {
    printf("Hello world\n");
    return;
  } 

into this

/* JNI implementation - HelloJNI.c */

#include "HelloWorld.h"
#include "jni.h"
#include  "stdio.h"

JNIEXPORT void JNICALL Java_HelloWorld_print(JNIEnv *env, jobject obj)
{
  printf("Hello world\n");
  return;
}

for every JNI implementation of C ? Because from my understanding, if the answer is yes, i need to rewrite 100 methods if there's 100 methods in a .c file which seems wrong.

thanks for answering and sorry for noobies.


Solution

  • The JNI interface stuff is only needed on the boundary between Java and C.

    So, even if you have a thousand functions, if you're only calling two of those via JNI directly (with the others being called by those two, or called by other functions that those two call, and so on), they're the only two you need to change.

    In other words, you can do something like:

    /* C implementation - HelloJNI.c */
    
    #include "HelloWorld.h"
    #include "jni.h"
    #include  "stdio.h"
    
    // Normal C function, not called directly from Java.
    
    static void output (char *str) {
      printf ("%s", str);
    }
    
    // JNI C function, called from Java.
    
    JNIEXPORT void JNICALL Java_HelloWorld_print(JNIEnv *env, jobject obj) {
      output("Hello world\n");
      return;
    }