In XS, when using sv_setpv or sv_setpvn, what happens to the char pointer?
Nothing. It is just read by those functions.
will perl create a SV around the pointer/string, and then free it eventually through normal GC?
No. (You wouldn't be able to do sv_setpv(sv, "foo"); if it did since "foo" can't be freed.)
or will perl copy the contents/string that the pointer points to into its own new allocated memory range
Yes. "Copies a string into an SV."
Similar question for SvPV, I get a pointer from perl, who is supposed to free this pointer?
It still belongs to the SV. You're just looking at the SV. Don't free it.
will perl GC/free it when the scalar goes out of scope?
When the scalar's refcount reaches zero.
is this the pointer of the actual data inside the SV or a newly allocated memory range with the bytes copied from the SV to the new memory range?
The former.
if I change the data at SvPV's pointer, will the SV be updated in perl land automatically?
Yes. Note that the content of the string are UTF-8 encoded and must be UTF-8 encoded if SvUTF8.
What is the SVPVX pointer?
SvPV stringifies the scalar if required before returning the string buffer.
SvPVX doesn't stringify, so you need to make sure there is a string buffer available to be obtained (using SvPOK) first.
How is SvPV_set different from sv_setpv?
One should use the macro version (SvPV_set).
SvPV_set just sets the PV field. You need to do any string copy, upgrading and flag setting yourself.
Does perl every "defragment" its SVs which would invalidated any pointers collected from SvPV or SvPVX?
A lot of things can invalidate the pointer. If the scalar is freed, or if it's type is changed such that it no longer has a PV, or if it's string is freed, or if the buffer moves due to reallocation during growth, etc.
You can't hold on to it for any length of time.
What happens if the scalar string in the scalar that pack gave a pointer to shrinks or expands, from Perl land, will the pointer from pack be still valid/the same?
No, not necessarily. Same as any other scalar.
You'll need to copy the string or keep a reference to the scalar. (Don't forget to increase its ref count if you keep a pointer to the scalar.)
Can a pointer made with 1 be freed with the other or vice versa?
No.