简体   繁体   English

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

[英]how to map with jna a byte[] to a void* buffer?

I have the following C function: 我有以下C函数:

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

This is usually call in C like: 通常在C中这样调用:

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

data is a struct, with the following: data是一个结构,具有以下内容:

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

And I have convert this to java, with jna with the following: 我已经将其转换为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);

And it gives me a "java.lang.Error: Invalid memory access" when I do the "clib.read" 当我执行“ clib.read”时,它给了我一个“ java.lang.Error:无效的内存访问”

Any idea how to go through this error??? 任何想法如何通过此错误???

I have tried to make a: int vox_playstr_read(int playdev, Pointer buffer, int count); 我试图做一个:int vox_playstr_read(int playdev,Pointer buffer,int count);

with

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

and it gives me the same result. 它给我相同的结果。

Please, any ideas to make it work? 拜托,有什么想法可以使它起作用?

Try creating the ByteBuffer with ByteBuffer.allocateDirect and then use byteBuffer.put(..) if you want to set any initial data. 尝试使用ByteBuffer.allocateDirect创建ByteBuffer ,然后如果要设置任何初始数据,请使用byteBuffer.put(..)。 Also, reset the position of the buffer, buffer.position(0). 同样,重置缓冲区的位置buffer.position(0)。

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

Read Edwin's reply here for the reason to use allocateDirect. 在此处阅读Edwin的回复,以了解使用allocateDirect的原因。

technomage's comments to the original post are exactly right. technomage对原始帖子的评论完全正确。 Explicitly, on the Java side, declare your JNA interface method as you plan to use it: 在Java端,明确地声明您打算使用JNA接口方法:

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

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

No need to use Buffer or ByteBuffer. 无需使用Buffer或ByteBuffer。 Also, depending on whether the read function is exported __cdecl or __stdcall, your JNA interface should extends Library or extends StdCallLibrary respectively. 另外,根据读取函数是导出__cdecl还是__stdcall,您的JNA接口应分别extends Libraryextends StdCallLibrary

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM