The below code works as is
Not quite.
should bechar* line[256]; // An array of 256 pointers, sizeof(line) == 2048
andchar line[256]; // An array of 256 chars, sizeof(line) == 256
should benewSVpv(line, sizeof(line)) // length($line) == 2048 (or 256)
newSVpv(line, strlen(line)) // length($line) == 3 -or- newSVpv(line, 0) // length($line) == 3
I'm pretty sure if a line length is longer than that, it'd be a buffer overrun (but I'm not positive).
No overrun. You'll just get part of the line in one loop, and the rest in subsequent loop passes.
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.
If you want to avoid truncating lines, you can use getline instead of fgets.
char* line = NULL; ssize_t line_size; while (1) { SV* line_sv; ssize_t len = getline(&line, &line_size, fh); if (len < 0) last; line_sv = newSVpvn(line, len); ... } if (line) free(line);
Could anyone in the know please help me understand how to create a new empty newSV() and use it in char* line's place
Why???
while (1) { // Actually allocates at least 256. SV* line_sv = newSV(255); // We know line_sv has a string buffer, so we can use SvPVX. char* line = SvPVX(line_sv); if (!fgets(line, 256, fh)) { break; } SvCUR_set(line_sv, strlen(line)); SvPOK_on(line_sv); ... // The callback may have changed line_sv, // so line might no longer be valid. line = SvPVbyte_nolen(line_sv); printf("c orig: %sc new: %s", line, modified_line); ... }
Maybe you want wanted to reuse line_sv instead of creating a new one for each loop pass, but that can be tricky because the callback could have changed it.
In reply to Re: Calling perl sub from a C loop using an SV as loop variable (as opposed to char)
by ikegami
in thread Calling perl sub from a C loop using an SV as loop variable (as opposed to char)
by stevieb
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |