Calling C functions

Q&A's, tips, howto's
Locked
jopython
Posts: 123
Joined: Tue Sep 14, 2010 3:08 pm

Calling C functions

Post by jopython »

Code: Select all

char hostname[128];
gethostname(hostname, sizeof hostname);
> (import "libnsl.so.1" "gethostname")
> gethostname<FEFC95F0>

> (set 'hostname nil)
> (gethostname hostname)
0

How to handle to the sizeof part?

jopython
Posts: 123
Joined: Tue Sep 14, 2010 3:08 pm

Re: Calling C functions

Post by jopython »

Never mind.
As per docs

Code: Select all

(set 'hostname (dup "\000" 64))
(set 'lpNum (pack "lu" (length str)))
(gethostname str lpNum)
(trim str)

Lutz
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Re: Calling C functions

Post by Lutz »

That's almost correct, but the length is 'unsigned int' not 'unsigned int *'. The C call pattern for gethostname is:

Code: Select all

gethostname(char *name, size_t namelen);
The 'size_t' in C is an 'unsigned int' (see man page for gethostname).

Code: Select all

(import "libc.dylib" "gethostname")   ; import the function
(set 'host (dup "\000" 64))           ; reserve enough space
(gethostname host 64)                 ; get the name into variable host
(get-string host) => "officemacmini.local"  ; cut of trailing 0's
You don't have to use 'get-string', your 'trim' is fine too, perhaps even better - self documenting.

The return value of 0 typically indicates a success of a function in C.

ps: there are situations where you must use 'get-string', i.e. when the argument is a raw number - address pointer to a string. 'get-string' takes both: a binary buffer or an address to a buffer as a number.

Locked