最近看到一个关于Java 线程创建的底层实现是通过native方法调用c++/系统函数,所以想搞一下java native
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"); } }
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); } }
javac TestNative.java javah -jni -encoding UTF-8 TestNative javac HelloNative.java javah -jni -encoding UTF-8 HelloNative
/* 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
#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); }