我想使用 C++ API 将 C 回调函数转换为 llvm 函数。 我的示例 C++ 函数如下所示。
extern "C" void bindMe(int(*compare)(const int a))
{
llvm::LLVMContext& context = llvm::getGlobalContext();
llvm::Module *module = new llvm::Module("top", context);
llvm::IRBuilder<> builder(context);
//I want to create the corresponding llvm function here which is called compareLLVM
llvm::BasicBlock *entry = llvm::BasicBlock::Create(context, "entrypoint", compareLLVM);
builder.SetInsertPoint(entry);
module->dump();
}
基本上我想将bindMe函数的参数(一个c回调函数)转换为相应的llvm函数。使用 API 可以实现类似的功能吗?
我将非常感谢任何想法。
谢谢
最佳答案
compare
是指向函数编译代码所在位置的指针。那里没有源代码 - 事实上,它甚至可能不是从 C 语言编译的 - 因此 LLVM 无法用它做太多事情,并且您无法将其转换为 LLVM Function
对象。
您可以做的是插入对该函数的调用:从该compare
指针创建一个LLVM Value
,并将其转换为适当的值类型,然后使用该强制转换指针作为函数创建一个调用指令。使用 API 插入这样的调用将类似于:
Type* longType = Type::getInt64Ty(context);
Type* intType = Type::getInt32Ty(context);
Type* funcType = FunctionType::get(intType, intType, false);
// Insert the 'compare' value:
Constant* ptrInt = ConstantInt::get(longType, (long long)compare);
// Convert it to the correct type:
Value* ptr = ConstantExpr::getIntToPtr(ptrInt, funcType->getPointerTo());
// Insert function call, assuming 'num' is an int32-typed
// value you have already created:
CallInst* call = builder.CreateCall(ptr, num);
关于c++ - 使用 c++ api 将 c++ 回调函数转换为 llvm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17540649/