Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do interpreters written in C and C++ bind identifiers to C(++) functions

I'm talking about C and/or C++ here as this are the only languages I know used for interpreters where the following could be a problem:

If we have an interpreted language X how can a library written for it add functions to the language which can then be called from within programs written in the language?

PHP example:

substr( $str, 5, 10 );
  • How is the function substr added to the "function pool" of PHP so it can be called from within scripts?

It is easy for PHP storing all registered function names in an array and searching through it as a function is called in a script. However, as there obviously is no eval in C(++), how can the function then be called? I assume PHP doesn't have 100MB of code like:

if( identifier == "substr" )
{
   return PHP_SUBSTR(...);
} else if( ... ) {
   ...
}

Ha ha, that would be pretty funny. I hope you have understood my question so far.

  • How do interpreters written in C/C++ solve this problem?
  • How can I solve this for my own experimental toy interpreter written in C++?
like image 263
sub Avatar asked Mar 30 '10 18:03

sub


1 Answers

Actually scripting languages do something like what you mentioned.
They wrap functions and they register that functions to the interpreter engine.

Lua sample:

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 */
like image 135
Nick Dandoulakis Avatar answered Nov 10 '22 14:11

Nick Dandoulakis