2013-10-22 31 views
1

我正在做C中的Forth解釋器。我無法決定如何更好地實現Forth字典。C中的函數指針表C

struct Word { 
    struct Word* next; 
     char* name; 
     int* opcode; 
     // int arg_count; 
} 
struct Dictionary { 
    struct Word words; 
    int size; 
} 

opcode是一個代碼序列 - 字的功能。因此,每個操作碼[i]對應於某些功能。我想它應該是一些表格,其元素爲[操作碼< - >功能指針]。但是如何實現呢?

我們不知道函數的大小。我們不能使用void *(或者我們可以?),因爲我們必須以某種方式使opcode執行該函數。

我該怎麼辦?

+0

這並不完全清楚。一個將整數映射到函數指針的表是完全可能的。這裏有什麼具體問題? –

+0

@OliCharlesworth,函數的簽名不同 – greensher

+0

「struct Word words;」 (與「struct Word * words」相反)通常不是好主意。 –

回答

3

這個定義有些變化是很常見的傳統福斯實現:然後

typedef int cell; 
typedef void code_t (struct Word *); 

struct Word 
{ 
    char name[NAME_LENGTH]; 
    struct Word *next; 
    code_t *code; 
    cell body[]; /* Upon instantiation, this could be zero or more items. */ 
}; 

詞典將通過next指針鏈接列表。這些字按順序分配,交織struct Word標題和body數據。

要執行一個詞,請致電word->code(word);code指向的功能可以決定如何處理body。正文可能是數據,也可能是你所說的「操作碼」。

冒號確定指標將有code指着這樣的事情:

void docolon (struct Word *word) 
{ 
    /* IP is a variable holding the instruction pointer. */ 
    rpush (IP); /* Push the current instruction pointer to the return stack. */ 
    IP = (struct Word *)word->body; /* Start executing the word body (opcodes). */ 
} 

而原始的單詞,例如+會看起來像

void plus (struct Word *word) 
{ 
    cell n1 = pop(); 
    cell n2 = pop(); 
    push (n1 + n2); 
} 
+0

IP =(struct word *)word-> body; – greensher

1

以下所有內容都基於一個假設:您要聲明函數指針。

typedef int (*OPCODE)(char *); 

struct Word 
{ 
    struct Word* next; 
    char* name; 
    OPCODE *opcode; 
    // int arg_count; 
}; 

opcode是一個函數指針,它返回一個整數,並採取了char *作爲參數的函數。關於函數指針的簡短教程的一個非常好的頁面是Lars Engelfried的The Function Pointer Tutorials