How to generate struct definition in the JNI header file with the javac or javah commands?

215 views Asked by At

Given a class such as:

class Position {
   float   x;
   float   y;

   public static native long instance();
   public static native float getX(long ptr);
   public static native float getY(long ptr);
   public static native long delete(long ptr);
}

when generating the native header file, I would like the struct definition corresponding to the fields of the class to be included in the headers. Something like:

struct Position {
   float x;
   float y;
}

Running the command

javac -classpath bin -d . -h jni src/Position.java

with Java 11 or the command

javah src/Position

with Java 8 doesn't generate the struct.

I found the desired behaviour described in docs for javah (not sure how valid they are currently) stating The .h file contains a struct definition whose layout parallels the layout of the corresponding class.

I would like to know if it's possible to achieve what I described above with javac -h. If not was it ever possible and if so, what were the reasons for the change? Moreover what alternatives do I have?

1

There are 1 answers

0
Kaan On

Question

What steps can be used to generate a JNI header file for the Java class below?

public class Position {
    float x;
    float y;
    public static native long instance();
    public static native float getX(long ptr);
    public static native float getY(long ptr);
    public static native long delete(long ptr);
}

Steps to follow

  1. Verify using JDK 11 – you mentioned trying versions 8 and 11, so I'm showing 11
    % javac -version
    javac 11.0.14
    
  2. Run javac using -h option and "." to write generated files to current directory
    % javac -h . Position.java 
    
  3. Verify contents of generated header file
    % cat Position.h
    /* DO NOT EDIT THIS FILE - it is machine generated */
    #include <jni.h>
    /* Header for class Position */
    
    #ifndef _Included_Position
    #define _Included_Position
    #ifdef __cplusplus
    extern "C" {
    #endif
    /*
     * Class:     Position
     * Method:    instance
     * Signature: ()J
     */
    JNIEXPORT jlong JNICALL Java_Position_instance
      (JNIEnv *, jclass);
    
    /*
     * Class:     Position
     * Method:    getX
     * Signature: (J)F
     */
    JNIEXPORT jfloat JNICALL Java_Position_getX
      (JNIEnv *, jclass, jlong);
    
    /*
     * Class:     Position
     * Method:    getY
     * Signature: (J)F
     */
    JNIEXPORT jfloat JNICALL Java_Position_getY
      (JNIEnv *, jclass, jlong);
    
    /*
     * Class:     Position
     * Method:    delete
     * Signature: (J)J
     */
    JNIEXPORT jlong JNICALL Java_Position_delete
      (JNIEnv *, jclass, jlong);
    
    #ifdef __cplusplus
    }
    #endif
    #endif