Java本地调用(JNI)
Posted xhBruce
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java本地调用(JNI)相关的知识,希望对你有一定的参考价值。
Java本地调用(JNI)
JNI: Java Native Interface(调用c/c++/其他本地代码,该接口提供了java与os本地代码互相调用的功能。
1、将调用java文件转化为.h
c/c++中 greeting 方法
class HelloNative
public static native void greeting();
javac -h ./ HelloNative.java (javah是1.8及以前版本)
生成 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: greeting
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_HelloNative_greeting
(JNIEnv *, jclass);
#ifdef __cplusplus
#endif
#endif
2、调用.h文件实现方法
Java_HelloNative_greeting
#include "HelloNative.h"
#include <stdio.h>
JNIEXPORT void JNICALL Java_HelloNative_greeting(JNIEnv* env, jclass cl)
printf("Hello Native World!\\n");
- cl -I “…\\jdk-16.0.1\\include” -I “…\\Java\\jdk-16.0.1\\include\\win32” -LD HelloNative.c -FeHelloNative.dll
(需要安装Visual Studio)
- gcc -mno-cygwin -D __int64=“long long” -I “…\\Java\\jdk-16.0.1\\include” -I “…\\Java\\jdk-16.0.1\\include\\win32” -shared -W1,–add-stdcall-alias -o HelloNative.dll HelloNative.c
(windows下载Cygwin)
- gcc -fPIC -I “…\\Java\\jdk-16.0.1\\include” -I “…\\Java\\jdk-16.0.1\\include\\win32” -shared -o HelloNative.so HelloNative.c
(Linux中gcc)
(gcc.exe -I "D:\\Program Files\\Java\\jdk-16.0.1\\include" -I "D:\\Program Files\\Java\\jdk-16.0.1\\include\\win32" -shared -Wl,--add-stdcall-alias -o HelloNative.dll HelloNative.c
成功)
Java调用dll库(或so库)
public class Main
public static void main(String[] args)
HelloNative.greeting();
static
System.loadLibrary("HelloNative");
javac Main.java
java Main
注意点
- 若HelloNative.java属于某个包,如
package com.xhbruce;
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_xhbruce_HelloNative */
#ifndef _Included_com_xhbruce_HelloNative
#define _Included_com_xhbruce_HelloNative
#ifdef __cplusplus
extern "C"
#endif
/*
* Class: com_xhbruce_HelloNative
* Method: greeting
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_com_xhbruce_HelloNative_greeting
(JNIEnv *, jclass);
#ifdef __cplusplus
#endif
#endif
以上是关于Java本地调用(JNI)的主要内容,如果未能解决你的问题,请参考以下文章