سؤال

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.

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

This thread suggests:

The existing mechanism which does work everywhere are the macros INT2PTR and PTR2IV (in perl.h)

From perldoc perlguts:

Because pointer size does not necessarily equal integer size, use the follow macros to do it right.

PTR2UV(pointer)
PTR2IV(pointer)
PTR2NV(pointer)
INT2PTR(pointertotype, integer)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top