首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >LLVM:"Export“类

LLVM:"Export“类
EN

Stack Overflow用户
提问于 2011-05-28 05:54:34
回答 1查看 465关注 0票数 4

我想使用LLVM从我的程序中调用以下代码:

代码语言:javascript
复制
#include <string>
#include <iostream>
extern "C" void hello() {
        std::cout << "hello" << std::endl;
}

class Hello {
public:
  Hello() {
    std::cout <<"Hello::Hello()" << std::endl;
  };

  int hello() {
    std::cout<< "Hello::hello()" << std::endl;
    return 99;
  };
};

我使用clang++ -emit-llvm -c -o hello.bc hello.cpp将这段代码编译成llvm字节码,然后我想从这个程序中调用它:

代码语言:javascript
复制
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <llvm/ExecutionEngine/JIT.h>
#include <llvm/LLVMContext.h>
#include <llvm/Module.h>
#include <llvm/Target/TargetSelect.h>
#include <llvm/Support/MemoryBuffer.h>
#include <llvm/Support/IRReader.h>

#include <string>
#include <iostream>
#include <vector>
using namespace std;
using namespace llvm;

void callFunction(string file, string function) {
  InitializeNativeTarget();
  LLVMContext context;
  string error;

  MemoryBuffer* buff = MemoryBuffer::getFile(file);
  assert(buff);
  Module* m = getLazyBitcodeModule(buff, context, &error);
  ExecutionEngine* engine = ExecutionEngine::create(m);    
  Function* func = m->getFunction(function);

  vector<GenericValue> args(0);    
  engine->runFunction(func, args);

  func = m->getFunction("Hello::Hello");
  engine->runFunction(func, args);
}

int main() {
  callFunction("hello.bc", "hello");
}

(使用g++ -g main.cpp 'llvm-config --cppflags --ldflags --libs core jit native bitreader'编译)

我可以毫无问题地调用hello()函数。我的问题是:如何使用LLVM创建Hello类的新实例?当我调用Hello::Hello()时,我得到了一个分段错误

谢谢你的任何提示!

曼纽尔

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-05-28 10:08:57

在给定源上运行clang++ -emit-llvm不会发出Hello::Hello,而且即使发出了,m->getFunction("Hello::Hello")也找不到它。我猜它崩溃是因为func为空。

通常不建议直接从LLVM JIT调用非extern "C"的函数……我建议像下面这样编写一个包装器,并使用clang编译它(或者使用clang API,这取决于您正在做什么):

代码语言:javascript
复制
extern "C" Hello* Hello_construct() {
  return new Hello;
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6158093

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档