当前位置: 代码迷 >> 综合 >> A tiny C-like library(类C语言的库)
  详细解决方案

A tiny C-like library(类C语言的库)

热度:10   发布时间:2023-12-13 19:59:34.0
A tiny C-like library(类C语言的小库) A library usually starts out as a collection of functions, but if you 每一个库通常都会以一组函数开头,不过要是你用过第三方的库函数后, have used third-party C libraries you know there's usually more to 就会知道在C库函数中,通常会有更多的有用东西,毕竟生活中不仅仅只是行为,动作, it than that because there's more to life than behavior, actions, and 与方法。 functions. There are also characteristics (blue, pounds, texture, 除了上述以外,通常还会有一些特性(如:磅,蓝色,质地结构与亮度) luminance), which are represented by data. And when you start to 这些都会以数据表示出来。 deal with a set of characteristics in C, it is very convenient to clump 于是,在C语言中,在处理那些特性时,将它们组合在一个结构体中会很是方便的, them together into a struct, especially if you want to represent 这种情况在你想用结构体来表达多个类似的事物时更是如此。 more than one similar thing in your problem space. Then you can 这样,你就可以为每一个处理对象创建一结构体的变量。 make a variable of this struct for each thing. Thus, most C libraries have a set of structs and a set of functions   以这此思路,在大多数C语言库中会有一组结构体,并另有一组函数与之相应 that act on those structs. As an example of what such a system 作为上面所述原理的一个实例,我们现在考虑编程时经常用到的一个有用工具, looks like, consider a programming tool that acts like an array, but 这个工具用起来有点像数组,不过当运行创建时,它的大小会随时改着需要而改变。 whose size can be established at runtime, when it is created. I'll call 我们在此称之为“CStash”。虽说这是用C++写的,不过在C语言中它也有相同的形式。 it a CStash. Although it's written in C++, it has the style of what you'd write in C: //: C04:CLib.h // Header file for a C-like library // An array-like entity created at runtime typedef struct CStashTag { int size; // Size of each space int quantity; // Number of storage spaces int next; // Next empty space // Dynamically allocated array of bytes: unsigned char* storage; } CStash; void initialize(CStash* s, int size); void cleanup(CStash* s); int add(CStash* s, const void* element); void* fetch(CStash* s, int index); int count(CStash* s); void inflate(CStash* s, int increase); ///:~ A tag name like CStashTag is generally used for a struct in case 在需要在结构体内部对其部引用时,像CStashTag这样的标签通常会用在结构体中 you need to reference the inside itself. For example, when 经常会用到。 creating a linked list (each element in your list contains a pointer to 例如,当创建一个链表时,我们会需要一个指针用来指向下一个结构体变量, the next element), you need a pointer to the next struct variable, so 所以就会需要一种方式来在结构体判断这个指针的属性。 you need a way to identify the type of that pointer within the body. Also, you'll almost universally see the typedef as shown 就像上面CStash中所看到的那样,你也会在C库的每一个结构体定义中经常看到“typedef”关键字 above for every struct in a C library. This is done so you can treat 这样做是为了在应用时可以把结构体当作一个新的类型并像如下方式定义变量“CStash A, B, C;” the struct as if it were a new type and define variables of that like this: CStash A, B, C;
  相关解决方案