我认为适当的答案需要详细的论文。
基本上,应该有宿主操作系统提供的库加载和符号搜索工具的包装器。如果您的语言的核心数据类型在内部用单个 C 数据结构表示,则可以对库开发人员提出要求,即导出的 C 函数的参数和返回类型应该是该数据结构的对象。这将使数据交换更易于实现。如果您的语言具有某种形式的模式表达式和第一类函数,那么 C 函数的签名可能会以模式编写,并且库会搜索与等效签名匹配的函数。以下是 C 函数的一些伪代码及其在脚本中的用法:
/* arith.dll */
/* A sample C function callable from the scripting language. */
#include "my_script.h" // Data structures used by the script interpreter.
My_Script_Object* add(My_Script_Object* num1, My_Script_Object* num2)
{
int a = My_Script_Object_To_Int(num1);
int b = My_Script_Object_To_Int(num2);
return Int_To_My_Script_Object(a + b);
}
/* End of arith.dll */
// Script using the dll
clib = open_library("arith.dll");
// if it has first-class functions
add_func = clib.find([add int int]);
if (cfunc != null)
{
sum = add_func(10, 20);
print(sum);
}
// otherwise
print(clib.call("add", 10 20));
此处无法讨论更多实现细节。请注意,我们还没有谈到垃圾收集等。
以下链接中的可用资源可能会帮助您更进一步:
http://common-lisp.net/project/cffi/
http://www.nongnu.org/cinvoke/