java使用jni

编写java代码

注意没有包名

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14

public class WinTextLoad {

    public native void queryWindText();

    static {
        System.loadLibrary("CWinTextLoad");
    }

    public static void main(String... args){

        new WinTextLoad().queryWindText();
    }
}
1
2
3
4
5
# 生成class文件
javac -verbose WinTextLoad.java

#生成WinTextLoad.h头文件
javah -jni WinTextLoad

查看生成的头文件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class WinTextLoad */

#ifndef _Included_WinTextLoad
#define _Included_WinTextLoad
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     WinTextLoad
 * Method:    queryWindText
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_WinTextLoad_queryWindText
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

编写c语言源文件

1
2
3
4
5
6
7
8
9
#include <stdio.h>
#include "stdlib.h"
#include "WinTextLoad.h"

JNIEXPORT void JNICALL Java_WinTextLoad_queryWindText(JNIEnv *env, jobject o)
{
    printf("hello world");
    return;
}  

编译源码文件为dll文件

1
2
3
4
5
6
7
# 编译命令
gcc -m64  -Wl,--add-stdcall-alias  -I"I:/SDKMAN/JDK1.8/include" -I"I:/SDKMAN/JDK1.8/include/win32" -shared -o CWinTextLoad.dll CWinTextLoad.c

# 备用
gcc  -I"I:/SDKMAN/JDK1.8/include" -I"I:/SDKMAN/JDK1.8/include/win32" -shared -o CWinTextLoad.dll CWinTextLoad.c
# 备用
cl -II:/SDKMAN/JDK1.8/include -II:/SDKMAN/JDK1.8/include/win32 -LD CWinTextLoad.c -FCWinTextLoad.dll

将CWinTextLoad.dll文件放入 C:\Windows\System32

运行java源文件

1
java CWinTextLoad

如果java类带包名使用 c源文件的方法改为

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// java
package com.matosiki
public class WinTextLoad {
}


// c.源文件
JNIEXPORT void JNICALL Java_com_matosiki_WinTextLoad_queryWindText(JNIEnv *env, jobject o)
{
    printf("hello world");
    return;
}