首页 > 解决方案 > 如何在 JNA 和 C 之间对齐内存

问题描述

我需要在 linux 环境中提供带有 O_DIRECT 标志的直接读取操作。当前的读取操作似乎失败,因为缓冲区内存未对齐。如何对齐缓冲存储器?

我试过这个:

Native.getLibraryOptions(Linux_C_lib_DirectMapping.class).put(Library.OPTION_STRUCTURE_ALIGNMENT, Structure.ALIGN_DEFAULT);

但是读取过程再次失败。

这是测试代码:

int ha = libC.open("/var/test/writetest", 0x1000 | 0x100000 | 0x4000 | 0x80);
if(ha<0){
    System.out.println("Error opening file");
    return;
}else{
    byte[] bb=new byte[512];
    int readed=libC.read(ha, bb, bb.length);
    System.out.println("lasterr:" +Native.getLastError());
    System.out.println("Read size:" +readed);
    System.out.println(new String(bb));
    libC.close(ha);
}

这是当前的输出:

lasterr:22
Readeed:-1

这是 c lib JNA 映射:

package test;

import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Structure;

public class Linux_C_lib_DirectMapping implements Linux_C_lib {

    native public int open(String path, int flags);

    native public int close(int fd);

    native public int read(int fd, byte[] buffer, int count);


    static {
        try {
            Native.register("c");
            Native.getLibraryOptions(Linux_C_lib_DirectMapping.class).put(Library.OPTION_STRUCTURE_ALIGNMENT, Structure.ALIGN_DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

和这个:

package test;

public interface Linux_C_lib extends com.sun.jna.Library {

    public int open(String path, int flags);

    public int close(int fd);

    public int read(int fd, byte[] buffer, int count);

}

标签: clinuxjnafile-read

解决方案


这家伙找到了解决办法! http://www.nicecode.eu/java-streams-for-direct-io/

在 JNAInputStream 类中掠夺。

PointerByReference pntByRef = new PointerByReference();
posix_memalign(pntByRef, BLOCK_SIZE, BLOCK_SIZE);
bufPnt = pntByRef.getValue();       
buffer = new byte[BLOCK_SIZE];

推荐阅读