c - 如何在 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);
}
解决方案
这家伙找到了解决办法! 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];
推荐阅读
- blogger - 替换 Blogger 生成的拇指中的字符串
- python - 如何从 json 响应创建 Django 模型
- django - 如何将包含经度/纬度的列表更改为包含纬度/经度的列表 - Django?
- css - 如何让我的 CSS 过渡只适用于一个元素?
- javascript - 如何使用 Typescript 键入数组的值
- regex - 正则表达式用单个字符替换多次出现的字符
- python-3.x - Python。简单的计算器。从字符串中抓取算术运算符
- python - pytest repeat - 获取当前迭代次数
- r - 如何用另一张纸上的实际基因名称信息替换 DESeq2 rlogTransformation 矩阵中的行名?
- python - 2021 年 9 月 13 日 Google Drive API 更新如何影响使用 pydrive 进行身份验证