如何用jna将byte []映射到void *缓冲区?

时间:2013-10-29 13:32:44

标签: java c jna

我有以下C函数:

    int read(int dev, void* buffer, unsigned int count)

这通常用C语言调用:

    read(data->dev, data->buffer, 32000);

data是一个结构,包含以下内容:

    typedef struct {
         ssize_t dev; 
         char buffer[32000]; 
    } DATA;

我已将此转换为java,jna包含以下内容:

    public class Data{//not neccesary to extends of Structure, because is only used to package both variables together
          public int dev;
          public byte[] buffer;//in the constructor of the class set to 32000 elements
    }

   int read(int playdev, Buffer buffer, int count);

   //clib is the class to connect with  de C library

   ByteBuffer bf = ByteBuffer.wrap(data.buffer);
   clib.read(data.dev, bf , READ_SIZE);

当我执行“clib.read”时,它给了我一个“java.lang.Error:无效的内存访问”

知道怎么回事这个错误???

我试图做一个:         int vox_playstr_read(int playdev,Pointer buffer,int count);

    ByteBuffer bf = ByteBuffer.wrap(data.buffer);
    Pointer pbuf = Native.getDirectBufferPointer(bf);
    clib.read(data.dev, pbuf, READ_SIZE);

它给了我相同的结果。

请提出任何想法让它发挥作用吗?

2 个答案:

答案 0 :(得分:1)

尝试使用ByteBuffer.allocateDirect创建ByteBuffer,然后如果要设置任何初始数据,请使用byteBuffer.put(..)。另外,重置缓冲区的位置buffer.position(0)。

ByteBuffer bb = ByteBuffer.allocateDirect(values.length);
bb.put(values);
bb.position(0);

阅读Edwin的回复here,了解使用allocateDirect的原因。

答案 1 :(得分:1)

technomage对原帖的评论是完全正确的。显然,在Java端,在您计划使用它时声明您的JNA接口方法:

int read(int playdev, byte[] buffer, int count);

clib.read(data.dev, data.buffer, READ_SIZE);

无需使用Buffer或ByteBuffer。此外,根据读取函数是否导出__cdecl或__stdcall,您的JNA接口应分别extends Libraryextends StdCallLibrary