How to return list from Inline::C code?

K

kj

I'm attempting to hack the Perl internals, something I know very
little of. So I apologize ahead of time for the cluelessness of
this question.

I want to implement a function via Inline::C such that, depending
on context, it returns either a scalar or a list of two values.
(This function will access the internals of other variables, and I
want to make it as fast as possible, hence the decision to code it
in C).

Since C is not capable of optionally returning a scalar or a list,
I don't even know where to begin with this.

Any advice would be much appreciated. In particular, I'd love to
look at source code for a simple function (in C) that returns a
scalar or a list according to calling context.

Thanks!

kj
 
S

Sisyphus

kj said:
I'm attempting to hack the Perl internals, something I know very
little of. So I apologize ahead of time for the cluelessness of
this question.

I want to implement a function via Inline::C such that, depending
on context, it returns either a scalar or a list of two values.
(This function will access the internals of other variables, and I
want to make it as fast as possible, hence the decision to code it
in C).

Since C is not capable of optionally returning a scalar or a list,
I don't even know where to begin with this.

Any advice would be much appreciated. In particular, I'd love to
look at source code for a simple function (in C) that returns a
scalar or a list according to calling context.

As William Ahern pointed out, GIMME_V seems to be your friend here:

D:\pscrpt\inline\special>type gimme_v.pl

use warnings;
use Inline C => Config =>
BUILD_NOISY => 1;

use Inline C => <<'EOC';

void foo() {
Inline_Stack_Vars;

if(GIMME_V == G_SCALAR) {
printf("%s\n", "return scalar");
Inline_Stack_Reset;
Inline_Stack_Push(sv_2mortal(newSViv(42)));
Inline_Stack_Done;
Inline_Stack_Return(1);
}

if(GIMME_V == G_ARRAY) {
printf("%s\n", "return array");
Inline_Stack_Reset;
Inline_Stack_Push(sv_2mortal(newSViv(65537)));
Inline_Stack_Push(sv_2mortal(newSViv(65539)));
Inline_Stack_Done;
Inline_Stack_Return(2);
}

if(GIMME_V == G_VOID) {
printf("Nothing to do ... \n");
Inline_Stack_Void;
}

}



EOC

$x = foo();
print $x, "\n\n";

@y = foo();
print "@y\n\n";

foo();

__END__
D:\pscrpt\inline\special>perl gimme_v.pl
return scalar
42

return array
65537 65539

Nothing to do ...

Cheers,
Rob
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top