如何使用LLVM IRBuilder从外部DLL调用函数?

时间:2014-07-22 23:36:53

标签: llvm

如何从LLVM中调用外部DLL的函数?如何从LLVM代码调用DLL文件中定义的函数?

1 个答案:

答案 0 :(得分:7)

由于您的问题缺少重要信息,我猜您想要实现以下目标。我猜你将使用c / c ++接口,并且该函数具有签名void fun(void)。我还猜你将使用LLVM Builder来创建对这个函数的调用(而不是clang等)。

首先使用dlopen / loadlibrary动态加载函数并获取函数指针fnPtr

为函数的返回值

创建Type*
Type* voidType[1];
voidType[0] = Type::getVoidTy(getGlobalContext());
ArrayRef<Type*> voidTypeARef (voidType, 1);

为该功能创建Function*。您应该已经从初始化阶段开始Module* TheModule

FunctionType* signature = FunctionType::get(voidTypeARef, false);
Function* func = Function::Create(signature, Function::ExternalLinkage, "fun", TheModule);

使用addGlobalMapping创建功能映射。您应该从初始化阶段开始ExecutionEngine* TheExecutionEngine

TheExecutionEngine->addGlobalMapping(func, const_cast<void*>(fnPtr));

现在,在您想要呼叫的适当位置,您现在可以使用IRBuilder这样插入对该功能的调用。

Function *FuncToCall= TheModule->getFunction("fun");
std::vector<Value*> Args; // This is empty since void parameters of function
Value *Result = IRBuilder->CreateCall(FuncToCall, Args, "calltmp"); // Result is void
相关问题