Page 1 of 1

Calling C functions

Posted: Sat Dec 24, 2011 5:10 am
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?

Re: Calling C functions

Posted: Sat Dec 24, 2011 5:31 am
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)

Re: Calling C functions

Posted: Sat Dec 24, 2011 5:47 am
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.