如何调用指向C函数的指针

时间:2014-10-25 05:23:41

标签: llvm llvm-c++-api

我有一个指向函数的指针,我需要调用它而不需要通过llvm :: Module :: getOrInsertFunction。此示例不起作用:

static int add(int x, int y);
llvm::Value *one, *two;

llvm::Constant* addfn 
   = llvm::ConstantInt::get(JB->getIntPtrTy(DataLayout), (intptr_t)add); 
llvm::Type* args[] = { Int32Ty, Int32Ty };
llvm::FunctionType* ftype = llvm::FunctionType::get(Int32Ty, args);
addfn = llvm::ConstantExpr::getPointerCast(addfn, ftype);
CreateCall(addfn, one, two);

有办法吗?或者我必须调用getOrInsertFunction吗?

1 个答案:

答案 0 :(得分:0)

看起来很有效:

static int add(int x, int y) { return x + y; }

llvm::Constant* addfn 
  = llvm::ConstantInt::get(Builder->getIntPtrTy(DataLayout), (intptr_t)add);
llvm::FunctionType* ftype = 0;
{
    llvm::Type* args[] = { Int32Ty, Int32Ty };
    ftype = ftype->get(Int32Ty, args);
}
llvm::Constant* pp 
  = llvm::ConstantExpr::getIntToPtr(addfn, llvm::PointerType::getUnqual(ftype));
addfn = llvm::ConstantExpr::getPointerCast(pp, ftype->getPointerTo());
jit_value_t sum = JB->CreateCall2(addfn, Value1, Value2);