[#0x0032] Pointer Swizzling

  繼續學習。pointer swizzling有個很壞的翻譯叫“指針混寫”,翻譯得不知所云。

  以下來自Jargon File和Wikipedia。

 

  To convert external names, array indices, or references within a data structure into address pointers when the data structure is brought into main memory from external storage; this may be done for speed in chasing references or to simplify code (e.g., by turning lots of name lookups into pointer dereferences). The converse operation is sometimes termed ‘unswizzling'.

 

  Jargon File的這一段解釋得還是不怎麼清楚,看Wikipedia上的這個例子就很清楚了。

 

  In computer science, pointer swizzling is the conversion of references based on name or position to direct pointer references. It is typically performed during the deserialization (loading) of a relocatable object from disk, such as an executable file or pointer-based data structure. The reverse operation, replacing pointers with position-independent symbols or positions, is sometimes referred to as unswizzling, and is performed during serialization(saving).

 

  For example, suppose we have the following linked list data structure:

struct node {
        int data;
        struct node *next;
};

  We can easily create a linked list data structure in memory using such an object, but when we attempt to save it to disk we run into trouble. Directly saving the pointer values won't work on most architectures, because the next time we load it the memory positions the nodes now use may be in use by other data. One way of dealing with this is to assign a unique id number to each node and then unswizzle the pointers by turning them into a field indicating the id number of the next node:

struct node_saved {
        int data;
        int id_number;
        int id_number_of_next_node;
};

  We can save these records to disk in any order, and no information will be lost. Other options include saving the file offset of the next node or a number indicating its position in the sequence of saved records.

 

  When we go to load these nodes, however, we quickly discover that attempting to find a node based on its number is cumbersome and inefficient. We'd like our original data structure back so we can simply follow next pointers to traverse the list. To do this, we perform pointer swizzling, finding the address of each node and turning the id_number_of_next_node fields back into direct pointers to the right node.

 

  簡單地說來,就是內存中的節點間通過“邏輯”指針(實質是內存地址)連接,而將這些節點保存到磁盤時,“邏輯”指針就沒有任何意義了,需要變換一種方式來表示這些節點間的連接關係(這裏也不好叫做“物理”指針……),這個變換的過程稱爲unswizzling。反過來,將這些節點從磁盤load到內存中時的變換就是swizzling。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章