Re: wchar_t and XS

[email protected] (Marvin Humphrey)
Newsgroups perl.xs
Message-ID <[email protected]>
On Mon, Feb 27, 2012 at 04:29:57PM +0000, Alberto Simões wrote:
> I googled for that, and found a typemap, but I do not understand how  
> typemaps work.

Take a look at the Foo.c file that is generated off of your Foo.xs file.  XS
"typemaps" are not very sophisticated -- they're just strings that get
inserted into a template for an XS function and then expanded.  It so happens
that some variables are available ($var, $arg), but you seem to be using those
right already.

> My typemap looks like:
>
> ------ 8< ----------
>
>
> TYPEMAP
> wchar_t
>
> INPUT
> T_WCHAR
>    {
>    // Alloc memory for wide char string. This could be a bit more
>    // then necessary.
>    Newz(0, $var, SvLEN($arg), wchar_t);
>
>    U8* src = (U8*) SvPV_nolen($arg);
>    wchar_t* dst = (wchar_t*) $var;
>
>    if (SvUTF8($arg)) {
>       // UTF8 to wide char mapping
>       STRLEN len;
>       while (*src) {
>           *dst++ = utf8_to_uvuni(src, &len);
>           src += len;
>       }
>    } else {
>        // char to wide char mapping
>        while (*src) {
>            *dst++ = (wchar_t) *src++;
>        }
>    }
>    *dst = 0;
>    SAVEFREEPV($var);
>    }
> ------ 8< -------------

Looks good to me, aside from concerns about 16-bit wchar_t systems and code
points above the BMP. 

(Although I don't know what SAVEFREEPV does, I assume it sets up the memory
you allocated to be freed once the function you are wrapping returns.)

Cheers,

Marvin Humphrey
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.