rsteinke has asked for the wisdom of the Perl Monks concerning the following question:

Is there some way in an XSUB of verifying that a string or SV is a valid function reference without calling it? What about an instance/method pair of the sort used in call_method()?

Replies are listed 'Best First'.
Re: Verifying function references in XSUBs
by samtregar (Abbot) on May 20, 2002 at 08:00 UTC
    Sure. If you've got a reference you can check its type with the SvTYPE macro. For example (untested):

    if (SvROK(sv) && SvTYPE(sv) == SVt_PVCV) warn("sv is a code reference (CV) alright.");

    As for your second question, you can check that an sv is a reference to an object of (or derived from) a given class using sv_derived_from() (untested all the way):

    if (SvROK(sv) && sv_derived_from(sv, "Foo")) warn("sv isa Foo");

    And to check that a method is valid for a given class you can do something like (really untested):

    if (gv_fetchmethod(gv_stashpv("Foo", 0), "Foo::bar")) warn("succeeded in finding Foo::bar");

    Now, I doubt I answered your all your questions, but you weren't exactly clear about what you're trying to do. Maybe you can explain in more detail?

    -sam

      I think gv_fetchmethod() is sort of what I was looking for. In the situation I'm working with, perl passes to SV's to an XSUB. I verify (in one particular code branch) that the first is a reference to a blessed object, and that the second is a string. I would like to verify that the string is a valid method on the object before I call call_method(). The tricky bit is, I don't know the class name of the blessed object, I just have an instance reference. Is there some way to get the class name of the object?
        I think you might be able to use HvNAME(SvSTASH(sv)) for that. Give it a try and see if that works.

        -sam

Re: Verifying function references in XSUBs
by Zaxo (Archbishop) on May 20, 2002 at 06:09 UTC

    I doubt if this is a complete answer, but the C linker does static checking of function names and signatures. If the dll, libfoo.so, doesn't have a foofunc() in its symbol table, the linker errs out when you try to build an xs interface which provides &LibFoo::foofunc.

    After Compline,
    Zaxo

      What are you talking about? What does the C linker have to do with manipulating SVs inside an XSUB?

      -sam