in reply to Re^7: Perl calls C calls Perl CallBack: How Perl callback use the same interpreter/context as Perl caller?
in thread Perl calls C calls Perl CallBack: How Perl callback use the same interpreter/context as Perl caller?

Hi,

This is the C code that called from a Perl function: (allocation, construction, etc. was used when I didn't attempt to use the Perl parser of the calling function)

dTHX; // Returns NULL for my_perl :( // Call a PERL function dSP; /* Ini +tialize stack pointer */ ENTER; /* Eve +rything created after here */ SAVETMPS; /* ... +is a temporary variable. */ PUSHMARK(SP); /* Rem +ember the stack pointer */ XPUSHs(sv_2mortal(newSViv((unsigned int)cbCtx))); /* Pus +h callback context onto stack */ my_hash = newHV(); my_arr = newAV(); hv_store( my_hash, "aaaaaa", 6, newSViv(42), 0 ); for ( int i = 0; i < 50; i++ ) { av_push( my_arr, newSViv((unsigned int)i) ); } // Store reference to parameters on the HASH hv_store( my_hash, "bbbbbb", 6, newRV((SV*)my_arr), 0 ); XPUSHs( sv_2mortal(newRV((SV*)my_hash)) ); //PUTBACK; /* Mak +e local stack pointer global */ call_pv( funcName, G_SCALAR ); /* Cal +l the function */ retVal = POPi; /* POP + the return of the PERL function */ SPAGAIN; /* Ref +resh stack pointer */ PUTBACK; FREETMPS; /* fre +e that return value */ LEAVE; /* ... +and the XPUSHed "mortal" args */
  • Comment on Re^8: Perl calls C calls Perl CallBack: How Perl callback use the same interpreter/context as Perl caller?
  • Download Code

Replies are listed 'Best First'.
Re^9: Perl calls C calls Perl CallBack: How Perl callback use the same interpreter/context as Perl caller?
by salva (Canon) on Jul 08, 2014 at 14:27 UTC
    Under the hood, dTHX relies on Perl_get_context() to retrieve the context, so they are mostly equivalents.

    It occurs to me that it may be related to the way thread local storage (TLS) is managed on Windows, maybe it is not shared between DLLs.

      Hi,

      The system works under CYGWIN.

      It seemed to me that I should pass the Perl interpreter pointer from the Perl script itself to the C DLL. Can you please hint me about how to do it?


      Many thanks,

      Itamar

        Sure, you start the argument declarations for your C function prototypes with pTHX/pTHX_, and then pass then as the first argument aTHX/aTHX_. For instance:
        /* Your C function declarations */ int foo(pTHX) { ... } int bar(pTHX_ int a) { ... } /* In your XS code */ int foo_result = foo(aTHX); int bar_result = bar(aTHX_ 21);