2011-05-27 37 views
4

我想使用LLVM从我的程序调用此代码: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; 
    }; 
}; 

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

#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()

感谢您的任何提示!

曼努埃尔

回答

3

运行给定的源clang++ -emit-llvm不会发出你好你好::和m->getFunction("Hello::Hello")不会发现它,即使它被发射。我猜想它会崩溃,因为func为空。

试图从LLVM JIT中直接调用不是extern "C"的函数通常不推荐......我建议编写如下的包装器,然后用clang编译它(或者使用clang API,具体取决于你在做什么):

extern "C" Hello* Hello_construct() { 
    return new Hello; 
}