【问题标题】:Android ByteBuffer.asXxxBuffer ignores position?Android ByteBuffer.asXxxBuffer 忽略位置?
【发布时间】:2011-05-08 10:18:33
【问题描述】:

我正在尝试读取包含顶点和元素的内存映射文件,以便在 OpenGL 中进行渲染。该文件正确加载到 iPhone 应用程序中,但我无法理解如何在 Android 中执行相同操作。我一直在与 ByteBuffer、FloatBuffer 和 IntBuffer 作斗争,它们的行为的一个方面让我感到困惑。

以下代码尝试读取一个长度,为顶点数据设置一个 FloatBuffer,读取顶点数据之后的另一个长度,并为元素数据设置一个 ShortBuffer。

int lenVerts = data.asIntBuffer().get();
data.position(data.position() + 4);

verts = data.asFloatBuffer();
data.position(data.position() + lenVerts);

IntBuffer ib = data.asIntBuffer();
int lenElems = ib.get();
data.position(data.position() + 4);

elems = data.asShortBuffer();
data.position(data.position() + lenElems);

根据我对文档的解释,asIntBuffer 调用应该将缓冲区返回到从当前位置开始的字节,一直到缓冲区的末尾。换句话说,它应该忽略我通过调用data.position(data.position() + lenVerts) 跳过的顶点数据。

问题是它似乎没有这样做。无论我将什么值传递给data.position(...),对asIntBuffer 的调用总是会返回一个缓冲区到整个底层ByteBuffer。通过注意到lenVerts == lenElems(即,相同的值被读取两次,即使顶点和元素数据的大小不同)和data.capacity() == 4*ib.capacity()(即ByteBuffer 的字节数是原来的四倍),这一点得到了双重证实因为 IntBuffer 有整数)。

我做错了吗?我是否错误地解释了文档?

如何创建仅由底层 ByteBuffer 的一部分支持的 XxxBuffer?

【问题讨论】:

    标签: android bytebuffer


    【解决方案1】:

    我只花了几个小时来解决这个问题,直到注意到 Buffer.position() 被其他使用缓冲区作为参数的方法所忽略。我的解决方法是创建一个只保存所需字节的新缓冲区:

    int pos = 100;
    Buffer myBuffer; // old buffer containing ALL data
    byte[] tmpBuf = new byte[myBuffer.capacity()-pos];
    myBuffer.position(pos);
    myBuffer.get(tmpBuf);
    
    // Create new buffer:
    Buffer fixedBuffer = ByteBuffer.wrap(tmpBuf); // new buffer containing only required data
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-09
      • 1970-01-01
      相关资源
      最近更新 更多