How to translate parts of source program to library calls without writing a full parser?

65 Views Asked by At

To give an example:

Say I have a very simple library that allows C code to be called from another language L.

In order to use your C code from L you need to change certain constructs in your C code such as changing function types to void, replacing function parameters with a single library type etc. So your C code might change from something like this:

double foo(double bar, double baz) {
  return bar + baz;
}

to something like this:

void foo(LibraryArgs args) {
  double bar = args.get(1);
  double baz = args.get(2);
  setReturn(baz + bar);
}

and now your function can be called from L.

I'm trying to write a program that does this transformation automatically when it sees a function marked with some sort of annotation, perhaps something like:

@MakeCallableFromL
double foo(double bar, double baz) {
  return bar + baz;
}

But I can't seem to find a solution short of writing a near complete parser for C. Would there be a simpler approach to solving this sort of problem?

1

There are 1 best solutions below

1
On BEST ANSWER

There's a lot of parsing wrapper generators out there, chief among these SWIG (which is awesome, and horrible at the same time).

If you can't use SWIG or something like existing parsers:

I'd completely avoid changing the original code -- the C functions must be externally visible, anyway, so it's much much easier to just take the finished shared object, and just extract symbols from it, and generate wrapper code from scratch.

Depending on your framework, there's different options to do that. For gcc, nm will be the tool of choice, or objdump -t or objdump -T.

Because you asked for overhead: It will be negligible; a compiler will automatically optimize away most of the unnecessary things that would happen.