【问题标题】:Function pointers table in CC中的函数指针表
【发布时间】:2013-10-22 11:38:40
【问题描述】:

我正在用 C 语言做一个 Forth 解释器。我无法决定如何更好地实现 Forth 字典。

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

opcode 是一个代码序列 - 单词的功能。所以每个 opcode[i] 对应于某个函数。我想它应该是一些带有元素 [opcodefunction pointer] 的表。但是如何实施呢?

我们不知道函数的大小。我们不能使用 void* (或者我们可以?)因为我们必须以某种方式只让操作码执行该函数。

我该怎么办?

【问题讨论】:

  • 这一点都不清楚。将整数映射到函数指针的表是完全可能的。这里的具体问题是什么?
  • @OliCharlesworth,函数的签名不同
  • "结构词词;" (与“struct Word *words;”相反)通常不是一个好主意。
  • @greensher 在这种情况下,如果只有几个不同的函数类型,您可以使用联合,或者重写采用较少参数的函数以采用一些额外的参数以使其兼容,或者编写包装器职能。函数指针和空指针是不兼容的,你不能拥有一个通用的函数空指针。或者,完全忘记函数表并使用switch

标签: c function-pointers interpreter forth


【解决方案1】:

这个定义的一些变化在传统的 Forth 实现中很常见:

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);
}

【讨论】:

  • IP = (struct word *)word->body;
【解决方案2】:

以下所有内容均基于一个假设:您要声明函数指针。

typedef int (*OPCODE)(char *);

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

opcode 是一个函数指针,它指向一个返回整数并将char * 作为参数的函数。 The Function Pointer Tutorials 是 Lars Engelfried 的一个非常好的关于函数指针的简短教程。

【讨论】:

    猜你喜欢
    • 2018-07-28
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-23
    • 2010-11-19
    相关资源
    最近更新 更多