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

I'd like to return a coderef (for an iterator) from an XS function. I haven't a clue how to go about it.

Is it even possible? Does anyone know of any existing examples?

The only notion that crosses my mind so far is using eval_pv() or eval_sv() to bring that iterator into existence.

Better thoughts?


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
RIP an inspiration; A true Folk's Guy

Replies are listed 'Best First'.
Re: (XS): returning an iterator.
by salva (Canon) on Sep 23, 2010 at 09:19 UTC
    I did something similar for Sort::Key, emulating a closure in XS. The trick I used was to return a new XSUB with the state attached in a magic table.

    The source code is here. The function returning the XSUB closure is _multikeysorter and there are two auxiliary functions _xclosure_make and _xclosure_defaults to set and retrieve the data attached to the XSUB.

      You make it look simple enough. But... :) where does cv come from in the following line from XS_Sort__Key__multikeysort?

      AV *defaults = _xclosure_defaults(aTHX_ cv);

      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.
        It gets introduced by the XS macro.
Re: (XS): returning an iterator.
by ikegami (Patriarch) on Sep 23, 2010 at 03:19 UTC

    Instead of compiling code repeatedly, you could call a PP closure generator from XS.

Re: (XS): returning an iterator.
by Anonymous Monk on Sep 23, 2010 at 02:45 UTC