您可以让本机方法返回写入的字节数。然后在 Java 端相应地更新 ByteBuffer。
public class SomeClass {
/**
* @param buffer input/output buffer
* @return number of bytes written to buffer
*/
private native int nativeMethod(ByteBuffer buffer);
public void myMethod() {
ByteBuffer buffer = ByteBuffer.allocateDirect(100);
int written = nativeMethod(buffer);
if (written > 0) {
buffer.limit(written);
}
...
}
}
编辑
尝试在C端设置限制值也是有效的,所以我不知道为什么你有问题。
朴素的实现(没有缓存等):
static jint nativeMethod(JNIEnv *env, jobject obj, jobject buffer) {
jclass cls = env->GetObjectClass(buffer);
jmethodID mid = env->GetMethodID(cls, "limit", "(I)Ljava/nio/Buffer;");
char *buf = (char*)env->GetDirectBufferAddress(buffer);
jlong capacity = env->GetDirectBufferCapacity(buffer);
int written = 0;
// Do something spectacular with the buffer...
env->CallObjectMethod(buffer, mid, written);
return written;
}
在 Java 端进行检查时,会在缓冲区上设置限制。