【问题标题】:Strange behavior when reading text files from assets从资产中读取文本文件时的奇怪行为
【发布时间】:2012-07-22 10:45:29
【问题描述】:

我目前正在使用本机活动的东西和 GLES 2.0,我正在使用 ndk 从资产加载 GLES 的着色器。

这是简单着色器的来源:

顶点着色器:simple.vsh

attribute vec4 vPosition;
void main()
{
    gl_Position = vPosition;
}

片段着色器:simple.fsh

precision mediump float;
void main()
{
    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}

这是我用来加载着色器文件的代码

AAsset *shaderAsset= AAssetManager_open(app->activity->assetManager, path, AASSET_MODE_BUFFER);
size_t length = AAsset_getLength(shaderAsset);

LOGI("Shader source size: %d\n", length);


char* buffer = (char*) malloc(length);

AAsset_read(shaderAsset, buffer, length);   

LOGI("Shader source : %s\n", buffer);

AAsset_close(shaderAsset);
free(buffer);

当我运行应用程序时,我在 android logcat 中看到了这个:

 Shader source size: 71
 07-22 13:23:52.683 11135 11146 I native-activity: Shader source : attribute vec4 vPosition;
 07-22 13:23:52.683 11135 11146 I native-activity: void main()
 07-22 13:23:52.683 11135 11146 I native-activity: {
 07-22 13:23:52.683 11135 11146 I native-activity:     gl_Position = vPosition;
 07-22 13:23:52.683 11135 11146 I native-activity: }
 07-22 13:23:52.683 11135 11146 I native-activity: sP
 07-22 13:23:52.683 11135 11146 I native-activity: Shader source size: 86
 07-22 13:23:52.683 11135 11146 I native-activity: Shader source : precision mediump float;
 07-22 13:23:52.683 11135 11146 I native-activity: void main()
 07-22 13:23:52.683 11135 11146 I native-activity: {
 07-22 13:23:52.683 11135 11146 I native-activity:     gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
 07-22 13:23:52.683 11135 11146 I native-activity: }
 07-22 13:23:52.683 11135 11146 I native-activity: fs`

注意文件末尾的“sP”和“fs”。

我还在构建 xml 文件中为文件扩展名添加了“无压缩”,以防万一出现问题,但问题仍然存在。

有人知道是什么原因造成的吗?

【问题讨论】:

    标签: android c++ c android-ndk


    【解决方案1】:

    不知何故,尾随零不会进入资产。

    尝试使用

    // one extra char for the trailing zero
    char* buffer = (char*) malloc(length + 1);
    
    AAsset_read(shaderAsset, buffer, length);   
    
    // fix the string to be zero-terminated
    buffer[length] = 0;
    

    【讨论】:

    • 感谢分配。那解决了它。但这仍然困扰着我,这是为什么?我在我的机器上使用 zip 实用程序打开了 apk,我注意到文件末尾有一个额外的新行。
    • 我真的不知道,在这种情况下我更喜欢快速的解决方法 :) 也许他们将文件大小调整为 4 的倍数或 128 字节(您的小
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多