Skip to content
Prev 11177 / 12125 Next

[R-pkg-devel] Replacement for SETLENGTH

Hi Merlise!


Referring to here:

https://github.com/wch/r-source/blob/8ca367db0c94194f07ee7bcf4b883e9c5dc11e02/src/main/builtin.c#L832

It seems as though the object is only re-used if the new length is
equal to the old length.

If you use Rf_lengthgets, you will need to protect the return value.
The code you wrote that uses protect indexes looks correct, and the
reprotect is good because you no longer need the old object.

2 is the correct amount to unprotect. PROTECT and PROTECT_WITH_INDEX
(as far as I know) are the only functions that increase the size of
the protect stack, and so the only calls that need to be unprotected.
Typically, people define `int nprotect = 0;` at the start of their
functions, add `nprotect++;` after each PROTECT and PROTECT_WITH_INDEX
call, and add `UNPROTECT(nprotect);` immediately before each return or
function end. That makes it easier to keep track.

I typically use R_PreserveObject and R_ReleaseObject to protect
objects without a need to bind them somewhere in my package's
namespace. This would be that .onLoad() uses R_PreserveObject to
protect some objects, and .onUnload uses R_ReleaseObject to release
the protected objects. I probably would not use that for what you're
describing.


Regards,
    Iris
On Tue, Jan 14, 2025 at 11:26?PM Merlise Clyde, Ph.D. <clyde at duke.edu> wrote:
Message-ID: <CADNULg9fKRf3K6Q062D7X4rUJysO=9cWA1kFEjpSv3J-Oy0bYg@mail.gmail.com>
In-Reply-To: <CY8PR05MB100342EF92E6E169CA1067103C8182@CY8PR05MB10034.namprd05.prod.outlook.com>