gpt4 book ai didi

c - 遍历缓冲区设计问题

转载 作者:太空宇宙 更新时间:2023-11-04 06:11:28 26 4
gpt4 key购买 nike

我正在开发一个事件驱动的应用程序,想为系统的低级接口(interface)提供一个高级 API。我目前对如何将 errno 传播到调用堆栈有疑问。这是我当前的 API

typedef struct watcher_t watcher_t;

typedef struct event_iterator_t event_iterator_t;

event_iterator_t *poll_events(watcher_t *watcher,
int poll_timeout_millis,
void *buffer);

const char* take_event_path(void *event_buffer,
event_iterator_t *iterator);

问题是轮询事件的调用者目前除了使用errno 别无选择。我是说

#include <errno.h>

void *buf = //...
watcher_t *watcher_ptr = //...
event_iterator_t * iterator_ptr = poll_events(watcher_ptr, 1000, buf);
if(iterator_ptr == NULL){
perror("Error while getting iterator");
}

我不确定这种方法是否常用。将结果类型声明为 int 并将 event_iterator_t ** 声明为 out 参数有什么好处。

int poll_events(watcher_t *watcher, 
int poll_timeout_millis,
void *buffer,
event_iterator_t **out);

最佳答案

I'm not sure if such approach commonly used. Is there any benefits of declaring the result type as int and an event_iterator_t ** as out parameter.

这两种方法都很常见。但是当函数返回一个 int 结果代码时,它更容易成为线程安全的,API 也更容易记录。

我建议使用以下方法:

  • 返回一个整数作为结果代码
  • 将上下文处理程序作为第一个参数传递,其中将包含观察器、迭代器等。

例子:

int api_init_context(api_context_t *ctx);
int api_add_watcher(api_context_t *ctx, watcher_t *watcher);
int api_poll_events(api_context_t *ctx, int poll_timeout_millis, void *buffer);
int api_take_event_path(api_context_t *ctx, void *event_buffer);

关于c - 遍历缓冲区设计问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55336343/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com