jna传递byte数组
C++代码:
#include "stdafx.h" #include <iostream> using namespace std; extern "C" _declspec(dllexport) int __stdcall Add(int a, int b) { return a + b; } extern "C" _declspec(dllexport) BYTE* __stdcall Encode(BYTE* data, int dataSize, int* returnSize) { *returnSize = 50; BYTE* result = new BYTE[*returnSize]; for(int i = 0; i < *returnSize; i++) result[i] = 5 + i; return result; }
Java代码:
import com.sun.jna.Library; import com.sun.jna.Memory; import com.sun.jna.Native; import com.sun.jna.Platform; import com.sun.jna.Pointer; import com.sun.jna.WString; public class Program { public interface Lib extends Library { public int Add(int a, int b); public Pointer Encode(Pointer data, int dataSize, Pointer resultSize); } @SuppressWarnings("deprecation") public static void main(String[] args) { Lib lib = (Lib) Native.loadLibrary("..\\Debug\\Lib.dll", Lib.class); System.out.println(lib.Add(1,2)); Pointer ptr = new Memory(3); byte[] data = new byte[] {1,2,3}; ptr.write(0, data, 0, data.length); Pointer returnSize = new Memory(4); Pointer result = lib.Encode(ptr, data.length, returnSize); byte[] resultData = result.getByteArray(0, returnSize.getInt(0)); System.out.println(result); } }
桂棹兮兰桨,击空明兮溯流光。