Skip to content

[R-pkg-devel] Calling R's tempdir() from C

3 messages · Duncan Murdoch, Rodrigo Tobar

#
Dear all,

I want to create a temporary directory from within my C++ R extension. 
On the other hand, CRAN's policy dictates that one cannot write anything 
outside the boundaries of the session's temporary directory, so I need 
to create it exactly there.

The R API offers R_tmpnam and R_tmpnam2, both of which require the path 
of the directory where the new name will reside. This can be obtained 
using tempdir() in R, but I couldn't find anything similar in the R API. 
Am I missing anything too obvious?

I tried out giving a NULL dirname to R_tmpnam{,2}, hoping that even 
though it's not mentioned in the docs, they would internally use the 
session's tmp dir, but this simply crashed. When embedding R one could 
also use the R_TempDir global variable, but this is flagged as 
unofficial R API for extensions. Finally, the only solution I could find 
was to call the tempdir() R function from within my C++ extension. This 
works fine, but it bothers me that there not an equivalent entry point 
in R's API.

Any pointers would be appreciated. If I'm deeply misunderstanding 
something please also shoot.

Cheers,

Rodrigo
#
On 10/08/2018 12:01 AM, Rodrigo Tobar wrote:
Why not pass the result of tempdir() in your call from R to your C++ 
function, or in an initialization call for your package?  It won't 
change during a session.

Duncan Murdoch
#
Hi,
On 10.08.18 3:10 PM, Duncan Murdoch wrote:
This is indeed a good suggestion, but (my bad!) I forgot to mention: the 
place I need to use this is at dynlib loading time (i.e., when 
R_init_mypackage is called), so I don't have the flexibility to pass 
arbitrary arguments.

I guess this is a separate but related question, but it's not clear to 
me if in the process of loading a package, any particular piece of R 
code is guaranteed to execute before the library is loaded; otherwise I 
could pass down the information by setting an environment variable in R 
and read it from C++, or even perform all the directory creation logic 
at the R level.

Thanks again,

Rodrigo