Java用JNA调用dll : Invalid memory access
生活随笔
收集整理的這篇文章主要介紹了
Java用JNA调用dll : Invalid memory access
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
問題描述
java通過JNA調用C/C++ dll時,報Invalid memory access
問題原因
經過分析原因是數據類型不匹配問題
int &a 和 a 的區別?
C語言中的a是一個變量,儲存著值。&a是常量,是變量a的內存地址。一般的&a是用來賦值給指針的(int *p=&a ;),或者是作為函數的參數傳遞(地址傳遞)
在java中對應&a 指針地址的引用變量為 com.sun.jna.ptr.IntByReference 或者?byte[]
代碼實現
將dll 放到resources 下面
引入的 JNA 的 Maven配置
<dependency><groupId>net.java.dev.jna</groupId><artifactId>jna</artifactId><version>5.8.0</version></dependency>JAVA代碼實現?
package com.example.demo;import com.sun.jna.Library; import com.sun.jna.Native; import com.sun.jna.ptr.IntByReference; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;/*** jvm 64位程序執行64位dll* jvm 32位程序執行32位dll*/ @RestController @RequestMapping("/test") public class AddController {public interface AddLib extends Library {AddLib instance = Native.load("lib64/test", AddLib.class);//int Add1(byte[] a,byte[] b); // 對應C 語言程序 int Add1(int &a,int &b)//int Add1(Object a, Object b);// 對應C 語言程序 int Add1(int &a,int &b)int Add1(IntByReference a, IntByReference b);// 對應C 語言程序 int Add1(int &a,int &b)int Add2(int a, int b); // 對應C 語言程序 int Add1(int a,int b)}@GetMapping("/add1")public static int Add1() {Integer a = new Integer(1258);Integer b = new Integer(2);return AddLib.instance.Add1(new IntByReference(a), new IntByReference(b)); // return AddLib.instance.Add1(toLH(a),toLH(b));}@GetMapping("/add2")public int Add2() {return AddLib.instance.Add2(2, 3);}@GetMapping()public String st() {return "hello test add";}public static void main(String[] args) {int d = AddLib.instance.Add2(112, 22);System.out.println("=============" + d);d = Add1();System.out.println(d);}public static byte[] toLH(int n) {byte[] b = new byte[4];b[0] = (byte) (n & 0xff);b[1] = (byte) (n >> 8 & 0xff);b[2] = (byte) (n >> 16 & 0xff);b[3] = (byte) (n >> 24 & 0xff);return b;}public static byte[] toHH(int n) {byte[] b = new byte[4];b[3] = (byte) (n & 0xff);b[2] = (byte) (n >> 8 & 0xff);b[1] = (byte) (n >> 16 & 0xff);b[0] = (byte) (n >> 24 & 0xff);return b;}}?
總結
以上是生活随笔為你收集整理的Java用JNA调用dll : Invalid memory access的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 问题 H: 迷宫问题
- 下一篇: Java使用钉钉定时发送邮件到企业邮箱