Chromium Embedded Framework中文文档 (使用C API)
简介
CEF的C API是由libcef DLL暴露的基于C的接口,cef_capi.h 头文件中定义的接口是由CEF translator tool自动生成的C++ API镜像。
引用计数
理解引用计数可能是使用CEF C API最困难的部分了,CEF使用引用计数概念类似于COM的概念,这里有一些基本的规则可以帮助你减少使用引用计数时的困难。
1. 当将一个结构传给它自己的成员函数时,不要进行引用计数的加、减操作:
struct->call_func(struct,...); // no reference counting change on 'struct'
2. 在将结构作为参数传给其它结构前,增加引用计数:
// Should have already added a reference to 'some_other_struct' struct->call_func(...,some_other_struct,...);
3. 在你使用完从别处以参数传过来的结构后,减少它的引用计数:
void my_func(...,some_other_struct,...) { // remove a reference from 'some_other_struct' after you're done using it }
4. 在传入一个处理程序前,增加它的引用,比如,cef_create_browser(),当API不再需要使用某一处理程序时,会移除它的引用。
5. 使用原子的引用计数实现,因为add_ref和release可能会跨线程调用,WinAPI InterlockedIncrement() 和 InterlockedDecrement() 函数可用于此目的。
6. 如果引用计算变成0,处理程序应该在已赋值给结构的releae()回调函数中删除自己:
// custom data structure that extends cef_handler_t
typedef struct _my_handler_t {
cef_handler_t handler; // cef_handler_t member comes first
// custom members here, including the reference count variable
} my_handler_t;
// allocate the custom data structure (already initialized to zero)
my_handler_t* my_handler = (my_handler_t*)calloc(1, sizeof(my_handler_t));
// set the size member of cef_base_t appropriately
my_handler->handler.base.size = sizeof(cef_handler_t);
// assign the release callback function (and the other callback functions)
my_handler->handler.base = my_release;
...
// release callback function implementation for my_handler_t
int CEF_CALLBACK my_release(struct _cef_base_t* base) {
// this cast works because cef_base_t is the first member of
// cef_handler_t and cef_handler_t is the first member of my_handler_t
my_handler_t* my_handler = (my_handler_t*)base;
// decrement the reference count (stored as a custom member of my_handler_t)
// free the my_handler_t structure when the reference count reaches zero
if(reference_count_is_zero)
free(my_handler);
}
7. 清除代码添加给结构的所有附加的引用(比如,在处理程序实现中保持cef_broswer_t指针的引用),最终的释放引用的机会是cef_handler_t::handle_before_window_closed()。
8. 如果没有任何的crash产生,在shutdown时也会命中DebugObjCt断言,那么就说明你正确的处理了引用计数。
标签:
CEF
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
2009-10-06 Predictably Irractional - 诚实与不诚实
2009-10-06 Predictably Irractional - 期望的效应
2009-10-06 Predictably Irractional - 让门都开着