From simon.urbanek at r-project.org  Sat Sep 15 14:40:29 2012
From: simon.urbanek at r-project.org (Simon Urbanek)
Date: Sat, 15 Sep 2012 08:40:29 -0400
Subject: [Rd] Question about copying arguments in C.
In-Reply-To: <CAA+5f=0UFS3d-mqcpFizY6=WnRES8_0AoPQ7N6hYP-5QgUHWvQ@mail.gmail.com>
References: <CAA+5f=0UFS3d-mqcpFizY6=WnRES8_0AoPQ7N6hYP-5QgUHWvQ@mail.gmail.com>
Message-ID: <0D319C1D-CA32-4FDC-96C1-B97D40A31DCC@r-project.org>


On Sep 14, 2012, at 11:10 PM, Simon Knapp wrote:

> Hi List,
> 
> I'd imagine this is a question that has been answered before, but I
> can't seem to track it down, sorry for the duplication if it has.
> 
> I am writing an interface for a C library and want to return an S4
> class from the 'constructing' method. One of the slots of the argument
> to be returned will be filled with one of the arguments passed to the
> function. My question is about whether I can directly pass arguments
> to the function directly to slots of the returned object (or to a
> return value more generally for that matter), or whether I have to
> copy them. If it is the latter, then how may I do this. The question
> is phrased in the following (simplified) code.
> 
> int constructThingy(int thingysInteger);
> 
> SEXP constructThingy(SEXP thingysInteger) {
>    SEXP ans, TClass, ti;
>    if(!isInteger(thingysInteger)) error("thingysIntegermust be an integer.");
>    if(constructThingy(INTEGER(thingysInteger)[0])) error("error in
> getting a thingy");
>    TClass = MAKE_CLASS("thingy");
>    PROTECT(ans = NEW_OBJECT(TClass));
> 
> 
>    // *****QUESTION STARTS HERE*****
>    // CAN I SAY:
>    SET_SLOT(ans, Rf_install("myInteger"), thingysInteger);
> 
>    // IF NOT, CAN I SAY
>    SET_SLOT(ans, Rf_install("myInteger"), AS_INTEGER(thingysInteger));
> 
>    // OR DO I NEED TO SAY
>    PROTECT(ti = allocVector(INTSXP, 1)); INTEGER(pns)[0] =
> INTEGER(thingysInteger)[0];
>    SET_SLOT(ans, Rf_install("myInteger"), ti);
>    // *****END OF QUESTION*****
> 
>    UNPROTECT(1); // or UNPROTECT(2) in latter case.
>    return ans;
> }
> 
> 
> 
> I think this is the same as asking whether the following is OK:
> 
> SEXP func(SEXP arg) {
>    return arg;
> }
> 

Yes.

In fact if you wanted to duplicate (e.g, if you want to modify an incoming argument and return the modified result), the proper way would be to use duplicate() and not the contortions your were trying.

Cheers,
Simon


> 
> 
> 
> 
> Thanks in advance,
> Simon
> 
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
> 
> 



[Rd] Question about copying arguments in C.
Simon Urbanek