stevieb has asked for the wisdom of the Perl Monks concerning the following question:
I've been learning about the Perl API lately, and just playing around a bit. I haven't coded in C in many years, so a lot of it is pretty much guessing.
The below code works as is, and I understand what's happening (per perlapi and perlcall), but I have a few questions.
Before the loop over the file, I define a char of 256 bytes. I'm pretty sure if a line length is longer than that, it'd be a buffer overrun (but I'm not positive).
What I'd like to do, is instead of a char, I'd like to create an empty newSV in its place, but I don't understand the size_t size reference for STRLEN arg in the docs. When I do sizeof(size_t), I get 8 bytes, which is no where near long enough. Can someone please point out my err?
My next issue is that when I do define manually a newSVpvf() I can't figure out to put it onto the stack properly; the perl sub never sees it.
Could anyone in the know please help me understand how to create a new empty newSV() and use it in char* line's place, and beyond that, an example of what I'd need to change once this is done?
use warnings; use strict; use Inline 'C'; c_replace('a.txt'); sub modify_from_c { my $line = shift; $line =~ s/0/5/; return $line; } __END__ __C__ #include <stdio.h> int c_replace(char* fname){ FILE *fh; fh = fopen(fname, "r"); if (! fh){ printf("Couldn't open file %s for reading.\n", fname); return 0; } char* line[256]; while (fgets(line, sizeof(line), fh)){ dSP; ENTER; SAVETMPS; PUSHMARK(SP); XPUSHs(sv_2mortal(newSVpv(line, sizeof(line)))); PUTBACK; int return_count = call_pv("modify_from_c", G_SCALAR); if (return_count > 1){ croak("invalid return count from modify_from_c()\n"); } SPAGAIN; char* modified_line = POPp; printf("c orig: %sc new: %s", line, modified_line); PUTBACK; FREETMPS; LEAVE; } fclose(fh); }
a.txt simply contains:
10 20 30 40 50
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Calling perl sub from a C loop using an SV as loop variable (as opposed to char)
by ikegami (Patriarch) on Mar 15, 2016 at 16:25 UTC | |
by stevieb (Canon) on Mar 15, 2016 at 16:32 UTC |