tags:

views:

181

answers:

2

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;

?

Note:

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;

Thanks!

+1  A: 

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;
}
Martin B
A: 

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?

SK-logic