C – Guidelines for implementing external function interfaces

Guidelines for implementing external function interfaces… here is a solution to the problem.

Guidelines for implementing external function interfaces

Now I’m working on a scripting language that doesn’t yet have FFI. I wonder what is the most convenient way to get it, let’s say I want to write it like a geek – I want to write FFI in the scripting language itself.

The programming language I need to interface in is C. So for the basics, I know libdl.so is my best friend. Obviously, this is not the only thing I need, but the most important of them.

I

only have a little idea of what else I need. I would like to get similar behavior from FFI to python ctypes have.

What do I need to know in order to do this? I knew there was some important magic in the data structures I needed to work with. How do I manage it so that I can do most of the important magic in the scripting language itself? I would get more use from this kind of magic, not just an external function interface. For example, I might want to pass C-like binary data to a file.

Solution

I think the appropriate answer needs to be detailed essay

Basically, there should be a wrapper around the library loading and symbol search tools provided by the host operating system. If your language’s core data types are internally represented by a single C data structure, you can ask the library developer that the parameters and return types of the exported C function should be objects of that data structure. This will make data exchange easier to implement. If your language has some form of pattern expressions and first-class functions, the signatures of C functions may be written in patterns, and the library searches for functions that match equivalent signatures. Here are some pseudocode for C functions and their use in scripts:

/* 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));

It is not possible to discuss more implementation details here. note
We haven’t said anything about garbage collection and the like yet.

The following links provide resources that may help you go one step further:

http://common-lisp.net/project/cffi/
http://www.nongnu.org/cinvoke/

Related Problems and Solutions