什么是 C 中的不透明指针? [英] What is an opaque pointer in C?

查看:31
本文介绍了什么是 C 中的不透明指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以知道 C 中不透明指针概念背后的用法和逻辑吗?

May I know the usage and logic behind the opaque pointer concept in C?

推荐答案

不透明指针是一种不显示底层数据细节的指针(来自字典定义:opaque:形容词;无法看到通过;不透明).

An opaque pointer is one in which no details are revealed of the underlying data (from a dictionary definition: opaque: adjective; not able to be seen through; not transparent).

例如,您可以在头文件中声明(这是我的一些实际代码):

For example, you may declare in a header file (this is from some of my actual code):

typedef struct pmpi_s *pmpi;

它声明了一个类型pmpi,它是一个指向不透明结构struct pmpi_s的指针,因此任何你声明为pmpi 将是一个不透明的指针.

which declares a type pmpi which is a pointer to the opaque structure struct pmpi_s, hence anything you declare as pmpi will be an opaque pointer.

该声明的用户可以自由编写如下代码:

Users of that declaration can freely write code like:

pmpi xyzzy = NULL;

不知道结构的实际定义".

without knowing the actual "definition" of the structure.

然后,在知道定义的代码中(即提供pmpi处理功能的代码,您可以定义"结构:

Then, in the code that knows about the definition (ie, the code providing the functionality for pmpi handling, you can "define" the structure:

struct pmpi_s {
    uint16_t *data;     // a pointer to the actual data array of uint16_t.
    size_t sz;          // the allocated size of data.
    size_t used;        // number of segments of data in use.
    int sign;           // the sign of the number (-1, 0, 1).
};

并轻松访问其中的各个字段,这是头文件用户无法做到的.

and easily access the individual fields of it, something that users of the header file cannot do.

有关不透明指针的更多信息,请访问 维基百科页面.

More information can be found on the Wikipedia page for opaque pointers..

它的主要用途是向库的用户隐藏实现细节.封装(尽管 C++ 人群会告诉你什么)已经存在很长时间了 :-)

The main use of it is to hide implementation details from users of your library. Encapsulation (despite what the C++ crowd will tell you) has been around for a long time :-)

您只想在您的图书馆上发布足够的详细信息,以便用户有效地使用它,不要更多.发布更多信息可为用户提供他们可能会依赖的详细信息(例如事实大小变量 sz 位于结构中的特定位置,这可能会导致他们绕过您的控件并直接对其进行操作.

You want to publish just enough details on your library for users to effectively make use of it, and no more. Publishing more gives users details that they may come to rely upon (such as the fact the size variable sz is at a specific location in the structure, which may lead them to bypass your controls and manipulate it directly.

然后,当您更改内部结构时,您会发现您的客户苦苦抱怨.如果没有这些结构信息,您的 API 将仅限于您提供的内容,并且您对内部结构的行动自由将得到维护.

Then you'll find your customers complaining bitterly when you change the internals. Without that structure information, your API is limited only to what you provide and your freedom of action regarding the internals is maintained.

这篇关于什么是 C 中的不透明指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆