gpt4 book ai didi

c++ - 使用 c++ api 将 c++ 回调函数转换为 llvm

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:49:55 25 4
gpt4 key购买 nike

我想使用 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 对象。

可以做的是插入对该函数的调用:从该比较指针创建一个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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com