检测C中的结构字段访问

rnu*_*nes 1 c parsing code-analysis c99 static-code-analysis

我想强制某个结构永远不会直接访问它的字段,总是使用结构函数.

例:

struct NoOutsideAccess { int field1;}
struct example {NoOutsideAccess f1;}

NoOutsideAccess noa;
example * ex;

&noa          // OK
&ex->noa      // OK
noa.field1;   // ERROR
ex->f1.field1 // ERROR
Run Code Online (Sandbox Code Playgroud)

我看过C解析器和分析工具,但我不确定我能用它们做到这一点.

我不想更改结构,因为它的字段将直接在其他模块中使用.在这种情况下,我想要一些脚本来指出它的使用位置,以便不应该改变它的模块.

但我确实发现了一个副本,不确定是否会匹配每个用法,但会给它一个镜头.

wkz*_*wkz 5

在C中创建不透明对象的一种方法是将定义隐藏在C文件中,并且只导出访问者原型以及头文件中对象的前向声明:

/* foo.h */

struct foo; /* forward declaration */

struct foo *foo_new (int bar, const char *baz);
void        foo_free(struct foo *foo);

int         foo_get_bar(struct foo *foo);
const char *foo_get_baz(struct foo *foo);
Run Code Online (Sandbox Code Playgroud)

然后执行:

/* foo.c */

struct foo {
    int bar;
    const char *baz;
};

/* implementations of foo_{new,free,get_bar,get_baz} */
Run Code Online (Sandbox Code Playgroud)

注意:由于外部代码不知道大小struct foo,你只能使用指向foo那里的指针(那就是它的位置foo_new).