如何使用LLVM IRBuilder从外部DLL调用函数? [英] How to call functions from external DLL using LLVM IRBuilder?
问题描述
如何从LLVM的外部DLL调用函数?如何从LLVM代码调用DLL文件中定义的函数?
How to call functions from external DLL from LLVM? How to call a function defined in a DLL file from a LLVM code?
推荐答案
由于您的问题缺少重要信息,我想您可能想要实现以下目标.我猜您将使用c/c ++接口,并且该函数具有签名void fun(void)
.我还猜想您将使用LLVM Builder创建对此功能的调用(而不是clang等).
As your question is missing vital information, I can guess that you want to achieve the following. I am guessing you will be using the c/c++ interface and that the function has a signature void fun(void)
. I also guess that you will be using LLVM Builder to create calls to this very function (and not clang or the like).
首先使用dlopen
/loadlibrary
动态加载函数并获取函数指针fnPtr
.
Start by using dlopen
/ loadlibrary
to dynamically load the function and get the function pointer fnPtr
.
为函数的返回值创建Type*
Type* voidType[1];
voidType[0] = Type::getVoidTy(getGlobalContext());
ArrayRef<Type*> voidTypeARef (voidType, 1);
为此功能创建一个Function*
.在初始化阶段,您应该已经有一个Module* TheModule
.
Create a Function*
for the function. You should have a Module* TheModule
already from initialization phase.
FunctionType* signature = FunctionType::get(voidTypeARef, false);
Function* func = Function::Create(signature, Function::ExternalLinkage, "fun", TheModule);
使用addGlobalMapping
创建到该功能的映射.在初始化阶段,您应该有一个ExecutionEngine* TheExecutionEngine
.
Use addGlobalMapping
to create a Mapping to the function. You should have a ExecutionEngine* TheExecutionEngine
from initialization phase.
TheExecutionEngine->addGlobalMapping(func, const_cast<void*>(fnPtr));
现在,在您要调用的适当位置,您现在可以像这样使用IRBuilder
插入对函数的调用.
Now, at the appropiate place where you want to call, you can now insert calls to the function using IRBuilder
like this.
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
这篇关于如何使用LLVM IRBuilder从外部DLL调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!