Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Inline::C - Why are my params in the stack?

by stevieb (Abbot)
on Dec 06, 2018 at 15:59 UTC ( #1226856=perlquestion: print w/replies, xml ) Need Help??
stevieb has asked for the wisdom of the Perl Monks concerning the following question:

So, I wrote a reply: Re: Make random numbers for fun, that generates random numbers using Inline::C, but afterwards realized that the parameters to my C function were always the first three elements of the stack ("return" of the array of random nums).

Here's the code, and the sample output. All other numbers in the list are random as expected:

use warnings; use strict; use Inline 'C'; my @random_numbers = getRand(1, 1000, 100); print "$_\n" for @random_numbers; __END__ __C__ #include <stdlib.h> void getRand (int start, int end, int iterations){ time_t t; srand((unsigned) time(&t)); inline_stack_vars; int i; for (i = 0; i < iterations; i++){ int randomNum = rand() % (end - start); inline_stack_push(sv_2mortal(newSViv(randomNum))); } inline_stack_done; }

Output:

1 1000 100 ...

I can't seem to find anything in the docs on how to avoid this. What's causing the parameters to be at the forefront of the stack?

Replies are listed 'Best First'.
Re: Inline::C - Why are my params in the stack?
by stevieb (Abbot) on Dec 06, 2018 at 16:01 UTC

    Ahhh, bloody heck. One minute after posting the question, Rubber Duck Debugging rescues me again.

    In Inline::C, it explains the Inline_Stack_Reset call:

    use warnings; use strict; use Inline 'C'; my @random_numbers = getRand(1, 1000, 100); print "$_\n" for @random_numbers; __END__ __C__ #include <stdlib.h> void getRand (int start, int end, int iterations){ time_t t; srand((unsigned) time(&t)); inline_stack_vars; inline_stack_reset; // <-- HERE int i; for (i = 0; i < iterations; i++){ int randomNum = rand() % (end - start); inline_stack_push(sv_2mortal(newSViv(randomNum))); } inline_stack_done; }

    That resolves the problem. Effectively, it resets the stack before appending to it.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1226856]
Approved by marto
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (3)
As of 2019-03-23 08:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    How do you Carpe diem?





    Results (114 votes). Check out past polls.

    Notices?