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

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

问题描述

可能重复:结果
  什么是一个不透明的价值?

我想知道背后C中的不透明指针概念的使用和逻辑?

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

推荐答案

这是不透明的指针之一,这是任何细节都透露出底层数据(从字典中的定义:不透明:形容词,不能被视为通过;没有透明的)

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).

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

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

typedef struct pmpi_s *pmpi;

这声明了一个类型 PMPI 这是一个指向不透明的结构结构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.

这声明的用户可以自由写code,如:

Users of that declaration can freely write code like:

pmpi xyzzy = NULL;

在不知道该结构的实际的定义

without knowing the actual "definition" of the structure.

然后,在code知道该定义(即code提供 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天全站免登陆