问题
How to call functions from external DLL from LLVM? How to call a function defined in a DLL file from a LLVM code?
回答1:
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).
Start by using dlopen / loadlibrary to dynamically load the function and get the function pointer fnPtr.
Create a Type* for the function's return value
Type* voidType[1];
voidType[0] = Type::getVoidTy(getGlobalContext());
ArrayRef<Type*> voidTypeARef (voidType, 1);
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);
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));
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
来源:https://stackoverflow.com/questions/24899568/how-to-call-functions-from-external-dll-using-llvm-irbuilder