簡體   English   中英

如何用jna將byte []映射到void *緩沖區?

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

我有以下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);

它給我相同的結果。

拜托,有什么想法可以使它起作用?

嘗試使用ByteBuffer.allocateDirect創建ByteBuffer ,然后如果要設置任何初始數據,請使用byteBuffer.put(..)。 同樣,重置緩沖區的位置buffer.position(0)。

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

在此處閱讀Edwin的回復,以了解使用allocateDirect的原因。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM