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);
        
    }

}

 

posted on 2021-01-11 16:18  空明流光  阅读(2420)  评论(2编辑  收藏  举报

导航