From @tep@n@@|nde|@r @end|ng |rom or@c|e@com  Thu Jan  9 15:05:26 2020
From: @tep@n@@|nde|@r @end|ng |rom or@c|e@com (Stepan)
Date: Thu, 9 Jan 2020 15:05:26 +0100
Subject: [Rd] Get memory address of an R data frame
In-Reply-To: <trinity-a73adb6e-7025-4545-9108-870c1a66fbfa-1578570504114@3c-app-mailcom-bs15>
References: <trinity-a73adb6e-7025-4545-9108-870c1a66fbfa-1578570504114@3c-app-mailcom-bs15>
Message-ID: <830d3acf-aa30-5f26-408d-f35b5f0cc2d9@oracle.com>

Hello Lille,

raw data of a data.frame (or more precisely a list, because data.frame 
is just a list with "data.frame" class) is an array of R specific data 
structures (SEXP), so a generic C function will not be able to work with 
them.

As a per-processing step, you may allocate an array for the pointers to 
the raw data of the columns yourself (there will be hopefully only a few 
compared to the size of the columns themselves). For this you'll need 
functions VECTOR_ELT to access the columns and DATAPTR to get their raw 
data (eventually TYPEOF to find out their type). Note that this won't 
work for a data frame that contains another list. If this memory layout 
doesn't work for you, then you may need to copy the whole data frame.

If you want to update the data from C, then keep in mind that

1) R vectors have value semantics and you should not be altering raw 
data of any vector unless you know that its not referenced from anywhere 
else -- otherwise you should make a copy, alter that copy instead and 
return it as the result from your C function.

2) R has generational garbage collector, so it *must* know about 
references between R objects and so you should use SET_VECTOR_ELT to 
update the data of a list (some would say that you can update the raw 
data if you really understand how the GC and R internals work, I would 
say: just don't)

Best,
Stepan

On 09. 01. 20 12:48, lille stor wrote:
> Hello,
>
> I would like for my C function to be able to manipulate some values stored in an R data frame.
>
> To achieve this, a need the (real) memory address where the R data frame stores its data (hopefully in a contiguous way). Then, from R, I call the C function and passing this memory address as a parameter.
>
> The question: how can we get the memory address of the R data frame?
>
> Thank you!
>
> L.
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://urldefense.proofpoint.com/v2/url?u=https-3A__stat.ethz.ch_mailman_listinfo_r-2Ddevel&d=DwICAg&c=RoP1YumCXCgaWHvlZYR8PZh8Bv7qIrMUB65eapI_JnE&r=neKFCw86thQe2E2-61NAgpDMw4cC7oD_tUTTzraOkQM&m=ob3rEYy-Pk9cOE-VcE6_0TaHPYjGJ4kHYZru_jqXf38&s=AV2V5CyECZzyfSMZdViD_co5mAGurLNEu4jhA_CTDsk&e=



[Rd] Get memory address of an R data frame
Stepan