java - 在 View 缓冲区上添加 float 组不会增加位置是否正常?

标签 java bytebuffer

如标题所示,这段代码:

    ByteBuffer vertexBuffer = GLBuffers.newDirectByteBuffer(3*Float.BYTES+3*Byte.BYTES);
    System.out.println(vertexBuffer.toString());
    vertexBuffer.asFloatBuffer().put(new float[]{1,2,3});
    System.out.println(vertexBuffer.toString());
    vertexBuffer.put(new byte[]{0,1,2});
    System.out.println(vertexBuffer.toString());

打印出以下内容:

java.nio.DirectByteBuffer[pos=0 lim=15 cap=15]
java.nio.DirectByteBuffer[pos=0 lim=15 cap=15]
java.nio.DirectByteBuffer[pos=3 lim=15 cap=15]

但是,理论上,我希望 View 缓冲区上的第一个 put 将位置从 0 增加到 3,第二个 put 从 3 增加到 6,以获得如下所示的结果:

java.nio.DirectByteBuffer[pos=0 lim=15 cap=15]
java.nio.DirectByteBuffer[pos=3 lim=15 cap=15]
java.nio.DirectByteBuffer[pos=6 lim=15 cap=15]

API 文档说:

public final FloatBuffer put(float[] src) Relative bulk put method  (optional operation). This method transfers the entire content of the given source float array into this buffer. An invocation of this method of the form dst.put(a) behaves in exactly the same way as the invocation dst.put(a, 0, a.length)

如果我们去看它提到的调用

public FloatBuffer put(float[] src, int offset, int length) Relative bulk put method  (optional operation). This method transfers floats into this buffer from the given source array. If there are more floats to be copied from the array than remain in this buffer, that is, if length > remaining(), then no floats are transferred and a BufferOverflowException is thrown. Otherwise, this method copies length floats from the given array into this buffer, starting at the given offset in the array and at the current position of this buffer. The position of this buffer is then incremented by length. In other words, an invocation of this method of the form dst.put(src, off, len) has exactly the same effect as the loop for (int i = off; i < off + len; i++) dst.put(a[i]);

它清楚地表明位置将会增加..

这是正常的还是我遗漏了什么?

编辑:行为相同:

ByteBuffer vertexBuffer = ByteBuffer.allocate(3*Float.BYTES+3*Byte.BYTES);

最佳答案

是的,没关系,因为实际上 position 在另一个对象中增加了,这是调用 vertexBuffer.asFloatBuffer() 时获得的引用。

换句话说,如果您将代码更改为:

    FloatBuffer floatBuffer = vertexBuffer.asFloatBuffer();
    floatBuffer.put(new float[]{1, 2, 3});
    System.out.println(floatBuffer.toString());

您将得到:

java.nio.ByteBufferAsFloatBufferB[pos=3 lim=3 cap=3]

关于java - 在 View 缓冲区上添加 float 组不会增加位置是否正常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34852818/

相关文章:

java - buff.getInt() & 0xffffffffL 是一个恒等式吗?

java - 将 ByteBuffer 传递给 jni,以便 C 代码在其内存地址中执行写操作

java - Apache POI 修改图表而不使用命名范围

java - 单个网页支持多语言

java - 如何在不同机器上调试部署在 tomcat 上的 Web 服务?

java - 检测 Bytebuffer 是否包含 int 或仅包含 byte[]

java - 这个 Java ByteBuffer 的行为有解释吗?

android - 如何在 JNI 中将 char[] 转换为 ByteBuffer?

java - 在Java中逐字母合并两个字符串?

java - IabHelper(类)Dispose(方法)未处理的异常