简介
JNI(Java Native Interface),它允许Java代码和其他语言(尤其C/C++)写的代码进行交互,只要遵守调用约定即可。
Controller
public class TestController { @ApiOperation(value = "调用c++dll或者so", httpMethod = "POST") @RequestMapping(value = "/call/test", method = RequestMethod.POST) public ReturnData testCallDll(@RequestBody @Valid IdParam param) { //入参1 结构体 YuandongBaseInfoNew.ByValue yuandongBaseInfoNew = new YuandongBaseInfoNew.ByValue(); yuandongBaseInfoNew.DataLeadCount = 4; yuandongBaseInfoNew.SampleRate = 256; yuandongBaseInfoNew.DataLength = 21896192; //入参3 字符串 String xmlPath ="E:\\VMRIZAse--1LLfiSW00zFPBb-0.xml"+"\0"; byte[] xmlPathBytes = xmlPath.getBytes(); //入参2 字符串 String reportPath = "E:\\VMRIZAse--1LLfiSW00zFPBb-0_diagnoise.xml"+"\0"; byte[] reportPathBytes = reportPath.getBytes(); YuandongInterface.YuandongLibrary.INSTANCE.AIEcgReportXml_A(yuandongBaseInfoNew,xmlPathBytes,reportPathBytes); System.out.println("reportPath:" + reportPath); return new ReturnData<>(reportPath); } }
c++ 接口
package com.test;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
public class YuandongInterface {
public interface YuandongLibrary extends Library {
YuandongLibrary INSTANCE = (YuandongLibrary) Native.loadLibrary((Platform.isWindows() ? "Report_1.0.3.9_x64_Release.dll" :
"libReport_1.0.3.9_x64_Release.so"),
YuandongLibrary.class);
/*声明的是dll中的方法*/
int AIEcgReportXml_A(YuandongBaseInfoNew.ByValue strucBaseInfo, byte[] inXmlFilePath, byte[] outReportFilePath);
}
}
结构体传参
package com.lepu.cardiot.holterECG.controller;
import com.sun.jna.Structure;
import java.util.Arrays;
import java.util.List;
public class YuandongBaseInfoNew extends Structure {
public int SampleRate; //采样率
public int DataLeadCount; //数据导联数
public int DataLength;
public byte[] StartTime = new byte[100];
public byte[] EndTime = new byte[100];
public byte[] Leads = new byte[100];
public byte[] LeadNames = new byte[100];
// 结构体传指针
public static class ByReference extends YuandongBaseInfoNew implements Structure.ByReference {
}
// 结构体传值
public static class ByValue extends YuandongBaseInfoNew implements Structure.ByValue {
}
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("SampleRate", "DataLeadCount", "DataLength", "StartTime", "EndTime", "Leads", "LeadNames");
}
}
注意
2.注意 c语言对应字符串要以“\0” 结尾