LLVM: "Export" 类

4
我想使用LLVM从我的程序中调用此代码:
#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字节码,然后我想从此程序中调用它:

#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()时,出现了分段错误。

谢谢任何提示!

曼努埃尔

1个回答

3
在给定的源代码上运行clang++ -emit-llvm不会产生Hello::Hello, 即使它被发射出来,m->getFunction("Hello::Hello")也无法找到它。我猜测它崩溃是因为func为空。通常不建议在LLVM JIT中直接调用非extern "C"函数... 我建议编写一个包装器,如下所示,并使用clang进行编译(或根据您的操作使用clang API):
extern "C" Hello* Hello_construct() {
  return new Hello;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接