Jade Dungeon

JNI

例子

  • Java的String要对应C++中的char *
#include <iostream>
#include <string>
using std::string;
using std::cin;
using std::cout;
using std::endl; 
 
#define MYLIBAPI extern "C" __declspec( dllexport ) 
 
//这的参数是必须的,也可以定义为.c头文件
MYLIBAPI double add(double a,double b);
MYLIBAPI double mul(double a,double b);
MYLIBAPI char * getString(char* a);
 
double add(double a,double b) { return a + b; }
 
double mul(double a,double b) { return a*b; }

//定义了一个返回java String类型的参数
char * getString(char* a) {
    char* b ="this is test";
    return strcat(a,b);
}
  • 生成库文件,如testDll.dll
  • Java中把C++生成的库文件放到合适的目录下:
  • Java中使用jna包来调用JNI接口

Maven中引入:

<!-- https://mvnrepository.com/artifact/net.java.dev.jna/jna -->
<dependency>
    <groupId>net.java.dev.jna</groupId>
    <artifactId>jna</artifactId>
    <version>5.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.java.dev.jna/jna-platform -->
<dependency>
    <groupId>net.java.dev.jna</groupId>
    <artifactId>jna-platform</artifactId>
    <version>5.3.1</version>
</dependency>

Java代码中调用的接口名字要和C++中定义的一致:

package com.binghe.jni;
 
import com.sun.jna.Library;
import com.sun.jna.Native;
 
/**
 * @author binghe
 * @description: 测试JNI程序
 */
public class JnaTest {

    public interface TestProject extends Library {
        TestProject INSTANCE = (TestProject) Native.load(
						"src/main/lib/testDll.dll", JnaTest.TestProject.class);
        public double add(double i, double j);
        public double mul(double i, double j);
        public String getString(String a);
 
    }
 
    public static void main(String[] args) {
        System.out.println(TestProject.INSTANCE.add(20.11,20.0));
        System.out.println(TestProject.INSTANCE.mul(16.9,20.89));
        System.out.println(TestProject.INSTANCE.getString("我现在正在测试dllgihjb"));
    }
}