我可以为 FFmpeg 中的不同指针类型创建和使用 C++ 智能指针吗?
分配:
AVCodecContext *avcodec_alloc_context3(const AVCodec *codec);
免费:
void avcodec_free_context(AVCodecContext **avctx);
用途:
int avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options);
然后是智能指针:
std::shared_ptr<AVCodecContext> av_codec_context(avcodec_alloc_context3(av_codec),
[](AVCodecContext* _context)
{
if (_context) avcodec_free_context(&_context);
});
avcodec_open2(av_codec_context.get(), av_codec, NULL)
这是正确的吗?
分配和使用:
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags);
其中 pm 是指向字典结构的指针。如果 *pm 为 NULL,则会分配字典结构并将其放入 *pm。
免费:
void av_dict_free(AVDictionary **m);
然后是智能指针:
std::shared_ptr<AVDictionary*> av_dict(new (AVDictionary*),
[](AVDictionary** _dict)
{
if (_dict)
{
if(*_dict)
av_dict_free(_dict);
delete _dict;
}
});
av_dict_set(av_dict.get(), "key", "value", 0);
这是正确的吗?
分配:
AVFormatContext *avformat_alloc_context(void);
免费:
void avformat_free_context(AVFormatContext *s);
用途:
int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options);
或
int avformat_open_input(AVFormatContext **ps, const char *url, const AVInputFormat *fmt, AVDictionary **options);
其中 ps 是指向用户提供的 AVFormatContext 的指针(由 avformat_alloc_context 分配)。可能是指向 NULL 的指针,在这种情况下,该函数会分配 AVFormatContext 并将其写入 ps 中。
然后是智能指针:
std::shared_ptr<AVFormatContext> av_format_context(avformat_alloc_context(),
[](AVFormatContext* _context)
{
if(_context)
avformat_free_context(_context);
});
avformat_find_stream_info(av_format_context.get(), NULL);
这是正确的吗?但是我如何将它与 avformat_open_input() 函数一起使用,它需要一个指向指针的指针,并且可能想通过该指针创建一个对象?
是正确的。
指针上的指针是不需要的,你只需要单个指针,即:
std::shared_ptr<AVDictionary> make_AVDictionaryPtr(const char *key,
const char *value,
int flags)
{
AVDictionary* p = nullptr;
av_dict_set(&p, key, value, flags); // "equivalent to" p = some_alloc(..)
return std::shared_ptr<AVDictionary>{
p,
[](AVDictionary* dict) {
if (dict) {
av_dict_free(&dict);
}
}
};
}
// ...
auto av_dict = make_AVDictionaryPtr("key", "value", 0);
av_dict_set(av_dict.get(), "key2", "value2", 0);
- 这是正确的吗?
是的
但是我如何将它与
函数一起使用,该函数需要一个指向指针的指针,并且可能想通过该指针创建一个对象?avformat_open_input()
至于2.如果你想直接使用的话