Skip to content
Prev 17387 / 63424 Next

wchar and wstring. (followup question)

Thanks for all of the help with my previous posts. This question might
expose much of my ignorance when it comes to R's memory managment and
the responsibilities of the programmer, but I thought I had better ask
rather than continue in my ignorance.

I use the following code to create a multi-byte string in R from my wide
character string in C.

int str_length;
char* cstr;
   
str_length = cel.GetAlg().size();
cstr = Calloc(str_length, char);
wcstombs(cstr, cel.GetAlg().c_str(), str_length);
SET_STRING_ELT(names, i, mkChar("Algorithm"));
SET_VECTOR_ELT(vals, i++, mkString(cstr));
Free(cstr);

My first question is: do I need the Free? I looked at some of the
examples in main/character.c, but I could not decide whether or not I
needed it. I imagined (I could not find the source for this function)
that mkString made a copy so I thought I would clean up my copy, but if
this is not the case then I would assume the Free would be wrong.

My second question is: It was pointed out to me that it would be more
natural to use this code:

SET_STRING_ELT(vals, i++, mkChar(header.GetHeader().c_str()));

instead of:

SET_VECTOR_ELT(vals, i++, mkString(header.GetHeader().c_str()));

However, the first line creates the following list element in R:

<CHARSXP: "Percentile">

Whereas, I want it to create as the list element:

"Percentile"

Which the second example does correctly. I had previously posted about
this problem and I believe that I was advised to use the second syntax,
but maybe there is a different problem in my code. I am trying to
construct a named list in R where my first line SET_STRING_ELT sets the
name of the list element and the second sets the value where the value
can be an INTEGER, STRING or whatever.

My third question is simply, why is wcrtomb preferred, the example i
based my code of of in main/character.c used  wcstombs.


Thanks again for all of the help.

jim
Prof Brian Ripley wrote: