首页 > 编程语言 > 详细

Java native编程

时间:2021-08-17 10:22:56      阅读:13      评论:0      收藏:0      [点我收藏+]

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编程

原文:https://www.cnblogs.com/youlingdada-top/p/15150792.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!