2011-05-27 34 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; 
}