llvm clang struct creating functions on the fly

I'm using LLVM-clang on Linux.

Suppose in foo.cpp I have:

struct Foo {
  int x, y;

How can I create a function "magic" such that:

typedef (Foo) SomeFunc(Foo a, Foo b);

SomeFunc func = magic("struct Foo { int x, y; };");

so that:

func(SomeFunc a, SomeFunc b); // returns a.x + b.y;



So basically, "magic" needs to take a char*, have LLVM parse it to get how C++ lays out the struct, then create a function on the fly that returns a.x + b.y;


If you really want to do this kind of stuff, you have to link in the whole CLang, and learn how to use its complicated and constantly changing API. Are you so sure you actually need it?

C++, being a compiled language (usually), can't do what you want it to do because, at run time, the compiler is no longer around to do the kind of parsing and code creation you would need for your magic function. This is a fundamental difference between compiled and interpreted languages.

If you really want to do what you are asking for, you would, in effect, have to write a parser that can parse C++ struct definitions and work out how LLVM lays out such a struct in memory. However, this is probably not really what you want to do.

What is the bigger problem you are trying to solve here? It sounds as if you might be able to use templates to do what you want -- along these lines:

template <class T>
int magic(T a, T b)
    return a.x + b.x;

Need Your Help

Splitting a list of files automatically

bash list split parallel-processing multitasking

This is my first post here although I've come here for solutions very very frequently!

Android exception - Unknown origin (possibly widget)

android exception

I have the following Android exception. It is reported by Bugsense and I cannot find out where it comes from as there is no reference to any class of my app.