Calling C functions

Started by jopython, December 23, 2011, 09:10:51 PM

Previous topic - Next topic

jopython


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

#1
Never mind.

As per docs

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

Lutz

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


gethostname(char *name, size_t namelen);

The 'size_t' in C is an 'unsigned int' (see man page for gethostname).



(import "libc.dylib" "gethostname")   ; import the function
(set 'host (dup "00" 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.