Call a perl routine with parameters
Asked Answered
M

1

8

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 ...);
Manatarms answered 11/4, 2014 at 15:37 Comment(1)
perlcall has a section labeled "Passing Parameters" for a reason. You do it by putting items onto the Perl stack.Aeolic
A
8

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.

Aeolic answered 11/4, 2014 at 16:47 Comment(2)
thanks for the suggestion! The example in the "Passing Parameters" section is exactly what I was looking for. Should have read the whole manual before asking :-(Manatarms
A slight neatening of that code is to use the mPUSH* family instead, as they mortalise the SV they push. Also there's a few specific ones; like mPUSHi for IVs and mPUSHp for PVs.Tenfold

© 2022 - 2024 — McMap. All rights reserved.