Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Python segfault when attempting to call environ using ctypes on libc?

Tested this both on Ubuntu and ArchLinux, I get

from ctypes import *
libc = CDLL('libc.so.6')
libc.environ()
Segmentation fault

Why?

like image 388
rapadura Avatar asked Jan 30 '12 10:01

rapadura


1 Answers

If i read the manpage correctly, environ is a char**, not a function. If you want to get the environ var, according to this post, you could do:

from ctypes import *
libc = CDLL('libc.so.6')
environ = c_char_p.in_dll(libc, 'environ')

But it return 'c_void_p(None)' for me, not sure why this happening (i know that i've declared as a char * only, but since it is returning None, their is nothing to dereference).

Anyway, you still have the "python" way:

import os
print os.environ

Or, if you search for a specific string in the environ using ctypes, for some function, you need to redefined the default restype:

from ctypes import *
libc = CDLL('libc.so.6')
getenv = libc.getenv
getenv.restype = c_char_p
print getenv('HOME')
like image 100
tito Avatar answered Nov 03 '22 21:11

tito