[英]File descriptors in C. Lugging them around vs static global
如果我正在編寫一個使用文件描述符進行處理的庫,那么何時應從lib_init()
返回它以供更高層的代碼使用並傳遞給我的lib_do_stuff()
調用,何時可以將其保留為私有我的C庫中的“成員”作為.c文件中的靜態全局變量?
如果我不認為我的庫用戶應該擁有控制權甚至不能訪問文件描述符,那么我是否可以只保留它,就像在C ++中那樣只是private
?
無論哪種方式,這樣做都有什么弊端?
通過示例擴展我的建議。
您的庫需要兩個(至少)頭文件:庫用戶包含的一個公共文件,以及僅包含在庫源文件中的一個私有文件。
公眾可能像
#pragma once
// This is all that is needed to declare pointers to the internal structure
typedef struct internal_structure STRUCTURE;
// The public API of your library
STRUCTURE *lib_init(void);
void lib_cleanup(STRUCTURE *s);
...
然后你有私有頭文件
#pragma once
struct internal_structure
{
int fd;
// Other members as needed
...
};
// Possible function prototypes of private functions
然后在庫源文件中同時包含公共和私有頭文件,並對黑盒結構使用STRUCTURE
:
#include <stdlib.h>
#include "public.h"
#include "private.h"
STRUCTURE *lib_init(void)
{
STRUCTURE *s = malloc(sizeof *s);
s->fd = open(...);
// Other initialization
...
return s;
}
void lib_cleanup(STRUCTURE *s)
{
// Other cleanup
...
close(s->fd);
free(s);
}
然后,庫的用戶僅包含公共頭文件,並使用您定義良好的API:
#include "public.h"
int main(void)
{
STRUCTURE *s = lib_init();
...
lib_cleanup(s);
return 0;
}
公用函數都應將STRUCTURE *
作為其參數之一,通常是它們的第一個參數,類似於lib_cleanup
函數。 然后,該函數可以根據需要使用結構及其成員。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.