I can't figure out how, or if it is possible, to access my'd variables from inside a C function.
I want to do something like: ==== my $VAR = "abc"; sub func { print "$VAR\n"; } func(); ====
It makes no difference whether $VAR is declared with 'my' or not. In either case perl's func() can see it.
But my stab at the perl api does not seem to do it: ==== my $VAR = "abc";
It makes no difference whether $VAR is declared with 'my' or not. In either case C's func() *can't* see it. You need to pass $VAR as an argument to func().
use Inline C => <<EOF;
In my inline scripts I always write the above line as: use Inline C => <<'EOF';
Haven't tested to see if there's an issue with leaving out the quotes.
void func() {
SV * VAR = get_sv( "VAR", FALSE );
if( VAR ) {
printf("VAR = %s\n", (char*)SvPV(VAR,PL_na));
} else {
printf("VAR is NULL\n");
}
}
Depending on your OS (I think) it may be necessary to leave a blank line between the closing } and the EOF. On my Win32 box, if I don't do that, the EOF cannot be found and the script aborts.
EOF
func(); ====
I would just write (untested):
================== my $VAR = 'abc';
use Inline C => <<'EOF';
void func(char * string) {
printf("%s\n", string);
}EOF
func($VAR); ==================
If you specifically want to pass the argument as an SV* instead of a char*, then you can change func() to:
void func(SV * string) {
char * out;
out = SvPV_nolen(string); /* convert SV to char */
printf("%s\n", out);
}This is all pretty basic. Not sure if that's because you've asked a basic question, or because I'm being a klutz and missing the point of your post. If it's the latter, then please ignore :-)
Perhaps what you *really* want to know is how to embed a perl variable in C ? If so, then 'perldoc perlembed' is about all that *I* can offer.
(There might even be something in the Inline C Cookbook on this - anyway, if you haven't already, take a look at 'perldoc Inline::C-Cookbook'.)
Hth.
Cheers, Rob
