Why does loading the libc shared library have “

2019-03-01 08:41发布

问题:

From https://en.wikipedia.org/wiki/Foreign_function_interface

the ctypes module can load C functions from shared libraries/DLLs on-the-fly and translate simple data types automatically between Python and C semantics as follows:

import ctypes
libc = ctypes.CDLL( '/lib/libc.so.6' )   # under Linux/Unix
t = libc.time(None)                      # equivalent C code: t = time(NULL)
print t

On Lubuntu 18.04

$ whereis libc
libc: /usr/lib/x86_64-linux-gnu/libc.a /usr/lib/x86_64-linux-gnu/libc.so /usr/share/man/man7/libc.7.gz

$ locate libc.so
/lib/i386-linux-gnu/libc.so.6
/lib/x86_64-linux-gnu/libc.so.6
/usr/lib/x86_64-linux-gnu/libc.so

$ ls -l /usr/lib/x86_64-linux-gnu/libc.so
-rw-r--r-- 1 root root 298 Apr 16 16:14 /usr/lib/x86_64-linux-gnu/libc.so

I was wondering why loading the libc shared library has "'LibraryLoader' object is not callable" error?

$ python3 --version
Python 3.6.5

$ python3

>>> import ctypes
>>> libc=ctypes.cdll("/usr/lib/x86_64-linux-gnu/libc.so")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'LibraryLoader' object is not callable


>>> libc=ctypes.cdll("/lib/x86_64-linux-gnu/libc.so.6")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'LibraryLoader' object is not callable


>>> libc=ctypes.cdll("/lib/i386-linux-gnu/libc.so.6")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'LibraryLoader' object is not callable

See also https://unix.stackexchange.com/questions/449107/what-differences-and-relations-are-between-the-various-libc-so

回答1:

You're confusing lower case cdll (which is a LibraryLoader) with upper case CDLL, which is the constructor for shared libraries.

This code will work as expected:

libc = ctypes.CDLL("/lib/x86_64-linux-gnu/libc.so.6")