chicken-users
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Chicken-users] length of string in C code


From: Jim Ursetto
Subject: Re: [Chicken-users] length of string in C code
Date: Mon, 28 Apr 2008 18:04:00 -0600

Heinrich,

One option is below.  Normally the quickest way to suss this stuff out is to
look at runtime.c, library.scm and chicken.h.  For example, in library.scm,
string-length is defined as

(define (string-length s) (##core#inline "C_i_string_length" s))

We can find the definition of C_i_string_length in runtime.c; it uses
C_header_size() to get the length.  Given that clue, you can find other uses of
C_header_size() on strings in runtime.c, such as in C_open_file_port(),
which gives us C_c_string() to get a non-null-terminated string.

The problem is you'll need backing store for the null-terminated result.
You could malloc, use a static buffer, or use a pre-allocated scheme-object.
It is usually much easier, if you can manage it, to pass in a c-string pointer
to your C function, so Chicken does the allocation behind the scenes.
The complete answer to your question really depends on what you're trying to do
in context.

On 4/28/08, Heinrich Taube <address@hidden> wrote:
> Hello,can someone please tell me how to turn something that is
> C_Stringp into either (1) A NULL terminated C string or (2) A buffer
> of chars plus the number of chars in the buffer?

 if ( C_truep(C_blockp(w)) && C_truep( C_Stringp( w ) )) {
    int len = C_header_size(w);
    char* buf = malloc(len+1);
    strncpy(buf, C_c_string(w), len);
        buf[len]='\0';
        /* use buf */
        free(buf);
 }




reply via email to

[Prev in Thread] Current Thread [Next in Thread]