先上java代码

public class HelloWorld{
	public static void main(String[] args){
		System.out.println("Hello, World");
	}
	public static int square(int input){
		int output = input * input;
		return output;
	}
	public static int power(int input, int exponent){
		int output,i;
		output=1;
		for(i=0;i<exponent;i++){
			output *= input;
		}
		return output;
	}
}

先编译java代码,生成class文件,javac HelloWorld.java

再上c代码

#include<stdio.h>
#include<jni.h>
 
JNIEnv* create_vm(JavaVM **jvm)
{
    JNIEnv* env;
    JavaVMInitArgs args;
    JavaVMOption options;
    args.version = JNI_VERSION_1_6;
    args.nOptions = 1;
    options.optionString ="-Djava.class.path=./";
    args.options = &options;
    args.ignoreUnrecognized = 0;
    int rv;
    rv = JNI_CreateJavaVM(jvm,(void**)&env, &args);
    if (rv < 0 || !env)
        printf("Unable to Launch JVM%d\n",rv);
    else
        printf("Launched JVM! :)\n");
    return env;
}
 
 
void invoke_class(JNIEnv* env)
{
    jclass hello_world_class;
    jmethodID main_method;
    jmethodID square_method;
    jmethodID power_method;
    jint number=20;
    jint exponent=3;
    hello_world_class =(*env)->FindClass(env, "HelloWorld");
    main_method =(*env)->GetStaticMethodID(env, hello_world_class, "main","([Ljava/lang/String;)V");
    square_method =(*env)->GetStaticMethodID(env, hello_world_class, "square","(I)I");
    power_method =(*env)->GetStaticMethodID(env, hello_world_class, "power","(II)I");
    (*env)->CallStaticVoidMethod(env,hello_world_class, main_method, NULL);
    printf("%d squared is %d\n",number,
        (*env)->CallStaticIntMethod(env,hello_world_class, square_method, number));
    printf("%d raised to the %d power is%d\n", number, exponent,
        (*env)->CallStaticIntMethod(env,hello_world_class, power_method, number, exponent));
}
 
 
int main(int argc,char **argv)
{
    JavaVM *jvm;
    JNIEnv *env;
    env = create_vm(&jvm);
    if(env == NULL)
        return 1;
    invoke_class(env);
    return 0;
}

 

编译c

gcc -D__int64="long long" -I/usr/java/jdk1.8.0_144/include -I/usr/java/jdk1.8.0_144/include/linux -o hello hello.c -L/usr/java/jdk1.8.0_144/jre/lib/amd64/server -ljvm

其中-I是头文件路径,-L是库文件路径,最后还有个-ljvm

如果还是找不到库文件,可以这样

vi /etc/ld.so.conf
增加/usr/java/jdk1.8.0_144/jre/lib/amd64/server
ldconfig

 

java提供jni,还有jna到jnr

https://blog.csdn.net/lanxuezaipiao/article/details/22668459
https://github.com/jnr/
https://github.com/jnr/jffi
https://github.com/jnr/jnr-ffi-examples