Perl newXS () with the addition of closure

I want to embed Perl in a C ++ application and am looking for a method to call in C ++ from perl via newXS (). In addition to the function pointer, I need the associated user pointer to the CV created by newXS (). The pointer contains a C ++ context. I do not want to use global variables for this. Is there a general way to do this?

In a wider context, the question, possibly in the weather, is it possible to add a closure to the CV created by newXS () , and how to refer to it when calling the function c that was registered with This. CvPADLIST () will seem like the perfect place, however for XSubs it seems unacceptable to use when PERL_IMPLICIT_CONTEXT is set (comment at the beginning of perl pad.c. Can this be ignored?). Is there any other place where I can post local CV data?

+5
source share
3 answers

Here is an ANY slot in CV that can be used for user data and is accessible using CvXSUBANY(cv) . For instance:

 CvXSUBANY(cv).any_ptr = my_ptr; 

This slot is typically used to store an index for XS ALIASes and a function pointer for XS INTERFACEs .

+3
source

One possibility is to apply the PERL_MAGIC_ext magic to the SV, as described in perlguts:

 int m_free (pTHX_ SV *sv, MAGIC* mg){ ... } STATIC MGVTBL my_vtbl = { 0, 0, 0, 0, m_free, 0, 0, 0 }; struct ctx; XS(XS_some_func) { ... MAGIC *mg; if ((mg = mg_findext((SV*)cv, PERL_MAGIC_ext, &my_vtbl))) { ctx *priv = (ctx *)mg->mg_ptr; } ... } 

And the magic assignment when creating a CV through newXS ():

  ctx c; ... CV *cv = newXS(index, XS_some_func, __FILE__); MAGIC *mg = sv_magicext((SV *)cv, 0, PERL_MAGIC_ext, &my_vtbl, (const char*)&c, sizeof(c)); 
+4
source

The simplest (and most likely) approach would probably be to make the context explicit - expose an object-oriented API and use methods instead of functions. When an instance of the new class is created in Perl code, you put the context in this object. When your XSUB is called as a method for this object, it will get the context as the first parameter (i.e. ST(0) ).

This is basically equivalent to a comment from the melpomene in terms of XS / C ++, but does not require additional closure of the shell.

If there is only one context for each process, using global variables will also be legal - perhaps a necessary evil. Compare also Safe storage of static data in XS .

I do not know which mechanism directly connects additional data with xsubs. It may be possible to draw some kind of magic with CV, but that sounds unnecessarily complicated if you cannot afford to put your context in a Perl object.

+2
source

Source: https://habr.com/ru/post/1271259/


All Articles