Accessing C constants (titles) from JNI (Java Native Interface)
•
Java
How do I access constants defined in C header files from the Java side (through JNI)?
I have a header file C_ header. C library of H:
// I'll try to get these values in java #define PBYTES 64 #define SBYTES 128 #define SGBYTES 128
Then I have this java code libbind_ jni. java:
package libbind;
public class libbind_jni {
static{
try {
System.load("libbind_jni.so");
} catch (UnsatisfiedLinkError e) {
System.err.println("Native code library Failed to load.\n" + e);
System.exit(1);
}
}
public static native String[] pubm(String seed);
Then in libbind_ jni. Run javah on Java and I generate JNI header file JNI_ header. h:
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: libbind_libbind_jni
* Method: pubm
* Signature: (Ljava/lang/String;)[Ljava/lang/String;
*/
JNIEXPORT jobjectArray JNICALL Java_lib_f_1jni_pubm
(jnienv *,jclass,jstring);
Then I put JNI in the library for JNI_ source. C wrote a small C code:
#include "jni_header.h"
#include "c_header.h"
#include <stdlib.h>
JNIEXPORT jobjectArray JNICALL Java_libbind_libbind_1jni_pubm
(jnienv *env,jclass cls,jstring jniSeed){
unsigned char vk[PBYTES];
unsigned char sk[SBYTES];
<whatever...>
}
– here you compile the libbind. Java library so
And Java source code J_ source. java:
import libbind.libbind_jni;
public class test {
/* trying to access constants from library (libbind.so) */
System.out.println(libbind_jni.PBYTES);
System.out.println(libbind_jni.SBYTES);
System.out.println(libbind_jni.SGBYTES);
}
public static void main(String[] args) {
test();
}
$javac test.java
test.java:5: cannot find symbol
symbol : variable PBYTES
location: class libbind.libbind_jni
System.out.println(libbind_jni.PBYTES);
So the question is: how do I access these definitions / constants in the C header file from Java?
thank you.
Solution
The simple answer is, you can't You must define the same value in Java
public static final int PBYTES = 64; public static final int SBYTES = 128; public static final int SGBYTES = 128;
Alternatively, you can define some native methods that return these values However, such macros cannot be accessed from Java
public static native int PBYTES(); public static native int SBYTES(); public static native int SGBYTES();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
