Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a perl routine with parameters

Tags:

c

perl

xs

I need to call a perl routine in my C program. The perl routine takes the following arguments: $a, $b, $c, where $a and $b are integers, $c is a string (may contain binary characters). According to perlcall, here are the means of making the call.

I32 call_sv(SV* sv, I32 flags);
I32 call_pv(char *subname, I32 flags);
I32 call_method(char *methname, I32 flags);
I32 call_argv(char *subname, I32 flags, char **argv);

Seems that I can only use call_argv(...), but there are two questions

  • how do I pass an integer to the perl routine
  • how do I pass a (binary) string to perl?

Wish there is a function like

I32 call_argv(char *subname, I32 flags, int numOfArgs, SV* a, SV* b, SV *c ...);
like image 633
packetie Avatar asked Apr 11 '14 15:04

packetie


People also ask

How do I pass a parameter in Perl subroutine?

You can pass various arguments to a subroutine like you do in any other programming language and they can be acessed inside the function using the special array @_. Thus the first argument to the function is in $_[0], the second is in $_[1], and so on.

How do you pass a variable to a subroutine?

Passing Arguments to a Subroutine When calling a subroutine, arguments can be passed to to it by writing them as a comma-delimited list inside the () . Inside the subroutine, these arguments are accessible using the special array @_ . The first argument to the function is in $_[0] , the second is in $_[1] , and so on.


1 Answers

See the Passing Parameters section of perlcall. Arguments are pushed on the Perl stack. call_argv isn't useful for passing anything other than strings. The calling convention would look something like

PUSHMARK(SP);
mPUSHi(some_integer);
mPUSHp(binary_data, len);
XPUSHs(some_SV_I_had_laying_around);
PUTBACK;
call_pv("sub_name", G_DISCARD);

or you can use call_sv if you have the subname in an SV*, or call_method to call a method by name on some object.

If the sub returns a value or values then you can call it with G_SCALAR or G_ARRAY and use the POP macros to access the return values; this is detailed in the following two sections. Don't forget to SPAGAIN.

like image 102
hobbs Avatar answered Oct 10 '22 02:10

hobbs