Java教程

Java native编程

本文主要是介绍Java native编程,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Java native 编程(环境jdk8 + winowsx64 + vc2017/MinGW)

最近看到一个关于Java 线程创建的底层实现是通过native方法调用c++/系统函数,所以想搞一下java native

Java native方法编写

  • TestNative.java
public class TestNative {
    static {
//        System.loadLibrary("TestNative");
        System.load("D:\\workspace\\C++\\TestNative\\x64\\Debug\\TestNative.dll");
    }

    public native static void test();

    public native static void test(String name);

    public native static int test(int a);

    public static void main(String[] args) {
        System.out.println(test(10));
        test();
        test("youlingdada");
    }

}

  • HelloNative.java
import java.util.Objects;

public class HelloNative {
    static {
        System.load("D:\\C++\\Test\\HelloNative.dll");
//        System.out.println(System.getProperty("java.library.path"));
//        System.loadLibrary("HelloNative");
    }

    public static native String sysHello(String s);

    public static void main(String[] args) {
        String s = sysHello("youlingdada");
        System.out.println(s);
    }
}

编译Java文件,并通过javah 生成对应的c/c++ 头文件

javac TestNative.java
javah -jni -encoding UTF-8 TestNative

javac HelloNative.java
javah -jni -encoding UTF-8 HelloNative
  • HelloNative.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class HelloNative */

#ifndef _Included_HelloNative
#define _Included_HelloNative
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     HelloNative
 * Method:    sysHello
 * Signature: (Ljava/lang/String;)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_HelloNative_sysHello
  (JNIEnv *, jclass, jstring);

#ifdef __cplusplus
}
#endif
#endif

编写c/c++实现方法

#include <stdio.h>
#include "pch.h"
#include "HelloNative.h"


JNIEXPORT jstring JNICALL Java_HelloNative_sysHello
(JNIEnv *env, jclass jobj, jstring name) {
	const char *s = env->GetStringUTFChars(name, 0);
	const char *str = (*env).GetStringUTFChars(name, 0);
	printf("name=%s\n", str);
	(*env).ReleaseStringUTFChars(name, str);
	char text[] = "youlingdada@163.com";
	return (*env).NewStringUTF(text);
}

注意点,这里我就实现HelloNative

  • System.loadLibrary(filename) 这里的filename 要放在src目录下即可
  • System.load(filepath) 绝对路径
  • c++实现的方法第二个参数必须为jclass 不能写jobject
这篇关于Java native编程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!