gpt4 book ai didi

java - 有没有办法用 JNI 设置 DirectByteBuffer 内存?

转载 作者:太空宇宙 更新时间:2023-11-04 06:49:11 25 4
gpt4 key购买 nike

出于某种原因,我必须使用目前无法从 JVM 直接访问的特定于 Linux 的 API,并且需要设计一个接受 ByteBuffer 的方法(这绝对不是因为某些性能原因)。这是它的样子:

//I need to call device-specific ioctl here
//and fill the ByteBuffer
public static native long putIntoByteBuffer(int fd, ByteBuffer buf);

生成的头文件为

JNIEXPORT jlong JNICALL Java_net_abcomm_PlatformSpecific_putIntoByteBuffer
(JNIEnv *, jclass, jint, jobject);

如何使用JNI获取给定的ByteBufferchar*?我可以使用 DirectBuffer,但我将仅限于使用 DirectBuffer,此外还会生成以下警告:

warning: DirectBuffer is internal proprietary API and may be removed in a 
future release
import sun.nio.ch.DirectBuffer;

还有GetDirectBufferAddress返回 void* 但仅限于 DirectBuffer

最佳答案

假设您将自己限制在公共(public)类及其公共(public) API 上,您有两种相对有效的方法来解决该问题,但它们的共同点是依赖于将数据放入 Java byte[]。这并不难:

/* error checks omitted for brevity; these are *not* optional */

char *cBytes = /* ... */;
size_t numCBytes = /* ... */;
jbyteArray javaBytes = /* ... */;

jsize numBytes = (*env)->GetArrayLength(env, javaBytes);
jbyte *bytes = (*env)->GetPrimitiveArrayCritical(env, javaBytes, NULL);
/* It is pretty safe to assume that jbyte is a character type, such as signed
char, in any C implementation that supports the JNI at all */
/* Assumes numCBytes <= numBytes; adjust as necessary if that may not be true: */
memcpy(bytes, cBytes, numCBytes);
(*env)->ReleasePrimitiveArrayCritical(env, javaBytes, bytes, 0);

请注意,如果 JNI 函数执行某种 I/O 来获取字节,它可能能够将它们直接读入 bytes(取决于 native 要求,而不是 JNI),但在那种情况下,您应该使用 Get/Release 例程的非Critical 版本。

话虽如此,将数据一直放入 ByteBuffer 的两个主要替代方法是

  • 如果缓冲区有Array(),则通过缓冲区的array()获取上述过程的byte[]方法。大功告成。

  • 如果缓冲区没有 hasArray(),或者如果您不想检查,则通过重新实例化它来获取 byte[],并通过上述过程加载后,通过缓冲区的批量 put(byte[])put(byte[], int, int) 将内容复制到缓冲区中方法。显然,这涉及相对于另一个替代方案的额外副本,并且它使用额外的临时对象。

我不建议假设一个特定的具体 ByteBuffer 子类或依赖非公共(public)方法。如果性能是重中之重,那可能值得考虑,但您似乎说不是。

关于java - 有没有办法用 JNI 设置 DirectByteBuffer 内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53922441/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com