in reply to How to call Encode::decode from Perl XS

Bases on my experience, it could be something like (untested)

int encode_loaded = 0; SV *m_encode = newSVpvs ("decode"); /* Or "Encode::decode", I'm not su +re */ SV *sv_enc = newSVpvs ("cp1252"); my_foo (char *buffer) { int result; if (!encode_loaded) { ENTER; load_module (PERL_LOADMOD_NOIMPORT, newSVpvs ("Encode"), NULL, + NULL, NULL); LEAVE; encode_loaded = 1; } PUSHMARK (sp); EXTEND (sp, 2); PUSHs (sv_enc); PUSHs (newSVpv (buffer)); PUTBACK; result = call_sv (m_encode, G_SCALAR | G_METHOD); SPAGAIN; if (result) { SV *encoded = POPs; /* Do more */ } PUTBACK; }

And some mortalization might be needed to not leak.


Enjoy, Have FUN! H.Merijn

Replies are listed 'Best First'.
Re^2: How to call Encode::decode from Perl XS
by Anonymous Monk on May 09, 2011 at 14:24 UTC
    all that load checking goes in the .pm file in the form of "use Encode...", kiss :)

      Yes and no. If you want a module to automatically load another module from XS, and not import all functions/methods, this is a cleaner way to do so. Of course you can croak/fail/die/barf/puke when a user tries to invoke something that he/she did not explicitely load, but as Encode is a CORE module I see no harm in hiding the require from XS and making the underlying module DWIM more.

      I agree that this is a grey/gray area and opinions may well differ if which case I think you should agree to disagree.

      XS is a different world and pulling the right strings is sometimes extremely hard compared to how easy perl made it in the language level itself.


      Enjoy, Have FUN! H.Merijn

        If you want a module to automatically load another module from XS, and not import all functions/methods,

        Not importing can be done from Perl too. It's not an advantage of XS. In Perl, not importing is done by using

        use Exporter qw( );
        or
        require Exporter;
        instead of
        use Exporter;

        As for automaticallydynamically loading a module, a need hasn't been mentioned.

        Update: Added first two sentences to clear up confusion mentioned in private message.

Re^2: How to call Encode::decode from Perl XS
by mje (Curate) on May 09, 2011 at 14:40 UTC

    Thanks Merijn, I'll look into this.