c++ - 为什么 AVFormatContext 指针在非全局结构对象中初始化,而在全局对象中初始化为 NULL?

标签 c++ struct ffmpeg global

这段代码和过滤_video.c差不多,ffmpeg文档中的一个示例代码。

在原来的例子文件中,有很多全局静态变量。这是第一个版本代码的一个片段(与原始示例相同):

static AVFormatContext *fmt_ctx;
static AVCodecContext *dec_ctx;

int main(int argc, char **argv) {

// ....  other code
    if ((ret = avformat_open_input(&fmt_ctx, filename, NULL, NULL)) < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n");
        return ret;
    }

// .... other code

}

由于所有这些变量都用于打开视频文件,因此我更愿意将它们分组。所以我的代码的目的是重新排列这些变量,使源文件更加结构化。

我想到的第一个想法是使用结构。

struct structForInVFile {
    AVFormatContext *inFormatContext;
    AVCodecContext *inCodecContext;
    AVCodec* inCodec;
    AVPacket inPacket;
    AVFrame *inFrame;
    int video_stream_index;
    int inFrameRate;
    int in_got_frame;
};

现在第二版代码变成了:

int main(int argc, char **argv) {

// .... other code
structForInVFile inStruct;

    if ((ret = avformat_open_input(&inStruct.inFormatContext, filename, NULL, NULL)) < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n");
        return ret;
    }

// .... other code

}

第二个版本的结果:代码无法在 avformat_open_input 上运行。没有错误信息。该程序静默退出。 通过调试发现:inStruct.inFormatContext: 0xffffefbd22b60000

在第 3 版代码中,我将 inStruct 设置为全局变量。 代码变为:

structForInVFile inStruct;

int main(int argc, char **argv) {

// .... other code
    if ((ret = avformat_open_input(&inStruct.inFormatContext, filename, NULL, NULL)) < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n");
        return ret;
    }

// .... other code

}

第三个版本的结果:代码有效。 通过调试发现:inStruct.inFormatContext: 0x0

所以我认为原因是:为了使 avformat_open_input 工作,AVFormatContext 应该被零初始化。 现在,问题是:

为什么 AVFormatContext 指针在非全局结构对象中初始化,而在全局对象中零初始化?

我不知道将结构对象定义为全局变量或非全局变量有什么区别。

最佳答案

简单。根据3.6.2 非本地对象的初始化中的C++ 标准:

具有静态存储持续时间 (3.7.1) 的对象应在任何其他初始化发生之前进行零初始化 (8.5)。

注意:您的问题是重复的。请在提问前更仔细地搜索 StackOverflow。

关于c++ - 为什么 AVFormatContext 指针在非全局结构对象中初始化,而在全局对象中初始化为 NULL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15511639/

相关文章:

C++ 类运算符自类型转换

c++ - 数组赋值无效?

我们可以在结构声明中使用#define 常量作为数组大小吗?

bash - 使用 ffmpeg 和 youtube-dl 从 Youtube 视频下载几秒钟的音频结果 [youtube] : No such file or directory error

encoding - 使用淡入淡出创建示例 mp3

c++ - PyS60 与塞类 C++

struct - 用另一个结构分配结构

c++ - 分配给结构映射的语法

video - 使用 ffmpeg 将图像添加到视频中,无法播放输出文件

c++ - 如何在线程c++11中调用二类成员函数中的一类成员函数