如何用C和C++编写的解释器将标识符绑定到C(++)函数

sub*_*sub 7 c++ interpreter

我在这里谈论C和/或C++,因为这是我所知道的唯一用于解释器的语言,其中以下可能是一个问题:

如果我们有一个解释型语言X,为它编写的库如何为该语言添加函数,然后可以从用该语言编写的程序中调用它?

PHP示例:

substr( $str, 5, 10 );
Run Code Online (Sandbox Code Playgroud)
  • 如何将函数substr添加到PHP的"函数池"中,以便可以从脚本中调用它?

PHP将所有已注册的函数名称存储在数组中并在脚本中调用函数时很容易.但是,由于C(++)中显然没有eval,那么如何调用该函数呢?我假设PHP没有100MB的代码,如:

if( identifier == "substr" )
{
   return PHP_SUBSTR(...);
} else if( ... ) {
   ...
}
Run Code Online (Sandbox Code Playgroud)

哈哈,那会很有趣.我希望你到目前为止理解我的问题.

  • 用C/C++编写的解释器如何解决这个问题?
  • 如何为我自己用C++编写的实验性玩具解释器解决这个问题?

Nic*_*kis 7

实际上脚本语言就像你提到的那样.
它们包装函数并将这些函数注册到解释器引擎.

Lua样本:

static int io_read (lua_State *L) {
  return g_read(L, getiofile(L, IO_INPUT), 1);
}


static int f_read (lua_State *L) {
  return g_read(L, tofile(L), 2);
}
...
static const luaL_Reg flib[] = {
  {"close", io_close},
  {"flush", f_flush},
  {"lines", f_lines},
  {"read", f_read},
  {"seek", f_seek},
  {"setvbuf", f_setvbuf},
  {"write", f_write},
  {"__gc", io_gc},
  {"__tostring", io_tostring},
  {NULL, NULL}
};
...
luaL_register(L, NULL, flib);  /* file methods */
Run Code Online (Sandbox Code Playgroud)