[Rd] [R] Passing character strings from C code to R
Tuszynski, Jaroslaw W.
JAROSLAW.W.TUSZYNSKI at saic.com
Fri Jul 15 21:41:46 CEST 2005
Thanks,
That fixed the problem.
Jarek
-----Original Message-----
From: ripley at stats.ox.ac.uk [mailto:ripley at stats.ox.ac.uk]
Sent: Friday, July 15, 2005 11:11 AM
To: Tuszynski, Jaroslaw W.
Cc: r-devel at stat.math.ethz.ch
Subject: Re: [R] Passing character strings from C code to R
Reading the posting guide would have shown you that R-help was quite
inappropriate, so I have moved this to R-devel.
allocString does not allocate a character vector, which is what you want to
set as an attribute (not a 'string', whatever that is). (It creates a
CHARSXP, a type that should not be user-visible directly and for which
STRING_ELT is inappropriate.)
You want something like (PROTECTS omitted):
Str = allocVector(STRSXP, 1);
SET_STRING_ELT(Str, 0, mkChar(comment));
There are many similar examples in the R sources for you to browse. There
is even a shortcut that manages the PROTECTS,
Str = mkString(comment);
(That allocString and mkString return different types indicate why I wrote
`whatever that is': the term is too loose to be useful.)
So you could just have
if(comment && strlen(comment)
setAttrib(Ret, install("com"), mkString(comment));
if(comment) Free(comment);
On Fri, 15 Jul 2005, Tuszynski, Jaroslaw W. wrote:
> Hi,
>
> I have a C code which produces array of integers and potentially a
> string, and I have problems passing the string out. Here is the
> relevant part of the
> code:
>
> 1 PROTECT(Ret = allocVector(INTSXP, n));
> 2 ret = (int*) INTEGER(Ret); /* get pointer to R's Ret */
> 3 for(i=0; i<n; i++) ret[i] = data[i];
> 4 Free(data);
> 5 i=1;
> 6 if (comment) { // comment was found
> 7 n = strlen(comment);
> 8 if(n>0) { // and it actually have some length
> 9 Rprintf(" '%s' %i\n", comment, n);
> 10 PROTECT(Str = allocString(n+1));
> 11 str = CHAR(STRING_ELT(Str, 0));
> 12 strcpy(str, comment);
> 13 Rprintf(" '%s' %i\n", str, n);
> 14 setAttrib(Ret, install("comm"), Str);
> 15 i=2;
> 16 }
> 17 Free(comment);
> 18 }
> 20 UNPROTECT(i);
>
> Print statement in line 9 gives right results, but program crashes
> before print statement in line 13.
> Any ideas to what am I doing wrong?
--
Brian D. Ripley, ripley at stats.ox.ac.uk
Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/
University of Oxford, Tel: +44 1865 272861 (self)
1 South Parks Road, +44 1865 272866 (PA)
Oxford OX1 3TG, UK Fax: +44 1865 272595
More information about the R-devel
mailing list