JNI、JNA 入门教程

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tony_328427685/article/details/83957388

一、JNI 入门教程

1.编写java测试类

package com.liu.jni;

public class JNILibrary {

    public native static void show();

    public native static int calc(int a, int b);

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

package com.liu.jni;

public class JNITest {

    public static void main(String[] args) {
        JNILibrary.show();
        System.out.println(JNILibrary.calc(3, 5));
    }
}

2.利用java类生成C头文件

cmd进入class文件根目录:

cd D:\jps-workspace\jni_jna\target\classes

执行命令:

javah -classpath . -jni com.liu.jni.JNILibrary

重命名com.liu.jni.JNILibrary.h为JNILibrary.h

3.编译生成C++动态库

创建动态库project:

复制JNILibrary.h到C++动态库project:

JNILibrary.h代码:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_liu_jni_JNILibrary */

#ifndef _Included_com_liu_jni_JNILibrary
#define _Included_com_liu_jni_JNILibrary
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_liu_jni_JNILibrary
 * Method:    show
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_com_liu_jni_JNILibrary_show
  (JNIEnv *, jclass);

/*
 * Class:     com_liu_jni_JNILibrary
 * Method:    calc
 * Signature: (II)I
 */
JNIEXPORT jint JNICALL Java_com_liu_jni_JNILibrary_calc
  (JNIEnv *, jclass, jint, jint);

#ifdef __cplusplus
}
#endif
#endif


JNIShared.cc代码:

#include <iostream>
#include "JNILibrary.h"

using namespace std;

JNIEXPORT void JNICALL Java_com_liu_jni_JNILibrary_show(JNIEnv *, jclass) {
    cout << "JNI Shared Library." << endl;
}

JNIEXPORT jint JNICALL Java_com_liu_jni_JNILibrary_calc(JNIEnv *, jclass,
        jint a, jint b) {
    return a + b;
}

然后编译生成动态库:

 

4.添加动态库到jni_jna

复制libshared_jni.dll到jni_jna工程目录

然后设置动态库位置:

5.测试JNITest

二、JNA入门教程

1.编写java测试类

package com.liu.jna;

import com.sun.jna.Library;
import com.sun.jna.Native;

public interface JNALibrary extends Library {

    JNALibrary INSTANCE = (JNALibrary) Native.loadLibrary("libshared_jna", JNALibrary.class);

    void show();

    int calc(int a, int b);
}

package com.liu.jna;

public class JNATest {

    public static void main(String[] args) {
        JNALibrary.INSTANCE.show();
        System.out.println(JNALibrary.INSTANCE.calc(3, 5));
    }
}

2.编译生成C++动态库

创建动态库project同上

JNAShared.cc代码:

#include <iostream>

using namespace std;

extern "C"  __declspec(dllexport) void show();

extern "C"  __declspec(dllexport) int calc(int a, int b);

void show() {
    cout << "JNA Shared Library." << endl;
}

int calc(int a, int b) {
    return a + b;
}

然后编译生成动态库:

3.添加动态库到jni_jna

复制libshared_jna.dll到jni_jna工程目录

4.测试JNATest

 

实例源码:

https://download.csdn.net/download/tony_328427685/10777544

展开阅读全文

没有更多推荐了,返回首页