It's a terrible title. I recently had the opportunity to come into contact with JNI, so as a reminder, ** "Until JNI beginners run native code (dll) on JNI" ** I would like to write easily.
~~ Click the link to read. ~~ "The one that executes native code from Java" (appropriate)
Later, if you get stuck with "Why did you use JNI to write in Java?", It may be that "It is better to write in Java without using JNI".
JNI needs to tweak the native code side. If you don't care about performance, consider JNA and SWIG. I can be happy. surely.
So let's match it properly. If you want to run on 64bit Java, use 64bit dll.
If not, tragedy may occur. Let's deal with it if necessary. If it's impossible, write a wrapper and control it exclusively ... (It's hard ...).
JNISample.java
)package com.hoge.jnisample;
public class JNISample {
//Native function declaration
private native String nativeFunction(String name);
//Load the module to run
static {
System.loadLibrary("libfuga");
}
//Native code execution
public String executeNative(String name) {
return this.nativeFunction(name);
}
}
Compile the above source to generate a class file (JNISample.class).
javac JNISample.java
Use the javah
command to generate a C (C ++) header. The command syntax is
javah -classpath {classpath} -d {Header output directory} {(package name.)name of the class}
This time, the directory structure is as follows.
java
└ com
└ hoge
└ jnisample
├ JNISample.java
└ JNISample.class
The command looks like this: (Run in the java
directory)
javah -classpath .\ -d ..\jniheader com.hoge.jnisample.JNISample
This will generate a header file in the jniheader
directory, which is on the same level as the java
directory.
com_hoge_jnisample_JNISample.h
)/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_hoge_jnisample_JNISample */
#ifndef _Included_com_hoge_jnisample_JNISample
#define _Included_com_hoge_jnisample_JNISample
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_hoge_jnisample_JNISample
* Method: nativeFunction
* Signature: (Ljava/lang/String;)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_hoge_jnisample_JNISample_nativeFunction
(JNIEnv *, jobject, jstring);
#ifdef __cplusplus
}
#endif
#endif
but,
jni.h
to the" Additional Include Directories ".jobject
, jstring
, etc.) needs conversion.Did it work?
JNI, it's not surprisingly difficult, isn't it? It was a more difficult image, but I was relieved at Ponkotsuenji. We hope you find this post useful to all JNI beginners.
Plenty of omissions in the second half. I honestly regret it. I wrote it for slide mode, but it's hard to read in normal mode.