llvm clang 结构动态创建函数
我在 Linux 上使用 LLVM-clang。
假设在 foo.cpp 中我有:
struct Foo {
int x, y;
};
如何创建一个“魔术”函数,使得:
typedef (Foo) SomeFunc(Foo a, Foo b);
SomeFunc func = magic("struct Foo { int x, y; };");
这样:
func(SomeFunc a, SomeFunc b); // returns a.x + b.y;
?
注意:
基本上,“magic”需要采用 char*,让 LLVM 解析它以了解 C++ 如何布局结构,然后动态创建一个返回 ax + by 的函数;
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你真的想做这种事情,你必须链接整个 CLang,并学习如何使用其复杂且不断变化的 API。您确定您确实需要它吗?
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++ 作为一种编译语言(通常)无法执行您希望它执行的操作,因为在运行时,编译器不再执行您的
magic 所需的解析和代码创建操作
函数。这是编译语言和解释语言之间的根本区别。如果您真的想做您所要求的事情,那么实际上您必须编写一个解析器来解析 C++ 结构定义并弄清楚 LLVM 如何在内存中布置这样的结构。然而,这可能并不是您真正想要做的。
您在这里试图解决的更大问题是什么?听起来好像您可以使用模板来做您想做的事情——沿着这些思路:
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: