How to call functions from external DLL using LLVM IRBuilder?

耗尽温柔 提交于 2019-12-05 03:54:35

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!