我有下面的示例程序,它将参数推送到 Perl 堆栈,然后调用“eval_sv”。示例 perl 语句被执行,但我无法检索从 C++ 作为 Perl 参数传递的变量。请让我知道我在以下程序中缺少什么
程序的输出
你好世界
测试
100测试完成
此行不打印 $a 和 $b 的值
string three = "print 'Test\n'; my $z = 100; print $a; print $b; print $z;";
这是我的代码:
#include <EXTERN.h>
#include <perl.h>
#include <string>
using namespace std;
string perlScript;
static PerlInterpreter *my_perl;
SV* my_eval_sv(I32 croak_on_error)
{
STRLEN n_a;
char *p1 = new char [perlScript.size()+1];
strcpy(p1, perlScript.c_str());
const char *p = p1;
int len = strlen(p);
dSP;
ENTER ;
SAVETMPS ;
PUSHMARK(SP) ;
int a, b;
a = 10;
b = 20;
PERL_SET_CONTEXT(my_perl);
XPUSHs(sv_2mortal(newSViv(a)));
PERL_SET_CONTEXT(my_perl);
XPUSHs(sv_2mortal(newSViv(b)));
/* Done with pushing pointers to Perl stack */
PUTBACK;
SV* sv1 = newSVpv(p, 0);
eval_sv(sv1, G_EVAL | G_KEEPERR);
SvREFCNT_dec(sv1);
SPAGAIN;
sv1 = POPs;
PUTBACK;
FREETMPS;
LEAVE;
if (croak_on_error && SvTRUE(ERRSV))
croak(SvPVx(ERRSV, n_a));
}
main (int argc, char **argv, char **env)
{
char *embedding[] = { "", "-e", "0" };
PERL_SYS_INIT3(&argc,&argv,&env);
my_perl = perl_alloc();
perl_construct(my_perl);
perl_parse(my_perl, NULL, 3, embedding, NULL);
PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
/*string perlBeginScript;
static const char * perlEndScript = "\
\n\
}\n\
";
if(perlBeginScript.length()==0)
{
perlBeginScript="EmbeddedPerl";
}
perlScript = "sub ";
perlScript += perlBeginScript;
perlScript += "{\n"; */
string one = "print 'Hello World\n'; ";
string two = "my $a = shift; my $b = shift; ";
string three= "print 'Test\n'; my $z = 100; print $a; print $b; print $z;";
string four = "print 'Testing complete\n';";
perlScript += one ;
perlScript += two;
perlScript += three;
perlScript += four;
//perlScript += perlEndScript;
/* Done with perl script to be executed */
my_eval_sv(TRUE);
PL_perl_destruct_level = 1;
perl_destruct(my_perl);
perl_free(my_perl);
PERL_SYS_TERM();
}