Search code examples
perlintptrxs

XS typemap for intptr_t


I'm trying to return an intptr_t type from some XS code:

intptr_t
my_func( self )
        myObjPtr self
    CODE:
        RETVAL = (intptr_t) self;
    OUTPUT:
        RETVAL

My typemap doesn't have anything about intptr_t, so of course dmake fails with Could not find a typemap for C type 'intptr_t'. I'm not sure if Perl even works with integers as big as intptr_t can be. If there's no good way to return this to Perl as a number, I'll just stringify it.


Solution

  • IV, Perl's signed integer format, is guaranteed to be large enough to hold a pointer. intptr_t is C's version of what Perl has had for a long time. (In fact, a ref is just a pointer stored in a scalar's IV slot with a flag indicating it's a reference.)

    But you don't want to cast directly to an IV as that can result in a spurious warning. As Sinan Ünür points out, use PTR2IV instead.

    IV
    my_func()
            myObjPtr self
        CODE:
            self = ...;
            RETVAL = PTR2IV(self);
        OUTPUT:
            RETVAL
    

    INT2PTR(myObjPtr, iv) does the inverse operation.