[LLVMdev] How to call a pointer that points to a C function

David Blaikie dblaikie at gmail.com
Mon Oct 27 10:06:49 PDT 2014


Easy way to answer questions like this is to write the obvious c code and
run it through ckang -emit-llvm to see what the IR looks like.
On Oct 27, 2014 10:05 AM, "CK Tan" <cktanx at gmail.com> wrote:

> Does anyone have a sample code on calling a c function thru pointer?
> Thanks.
>
> > On Oct 27, 2014, at 1:37 AM, David Chisnall <David.Chisnall at cl.cam.ac.uk>
> wrote:
> >
> > There is at least one error here, possibly two.
> >
> >> On 27 Oct 2014, at 07:46, C K Tan <cktanx at gmail.com> wrote:
> >>
> >> I have a pointer to a function that I need to invoke without going
> >> through llvm::Module::getOrInsertFunction. This example does not work:
> >>
> >> 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);
> >
> > The type that you want is not the function type, but the function
> *pointer* type.  ftype->getPointerTo() should give you the type that you
> need.
> >
> >> addfn = llvm::ConstantExpr::getPointerCast(addfn, ftype);
> >
> > I don't remember if this will just do casts between pointers or if it
> can also create inttoptrs, but you might need to be more explicit and ask
> for an inttoptr.
> >
> > David
>
> _______________________________________________
> LLVM Developers mailing list
> LLVMdev at cs.uiuc.edu         http://llvm.cs.uiuc.edu
> http://lists.cs.uiuc.edu/mailman/listinfo/llvmdev
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-dev/attachments/20141027/783c0adc/attachment.html>


More information about the llvm-dev mailing list