[Tutor] call a def/class by reference
alan.gauld at freenet.co.uk
Fri Sep 30 09:44:02 CEST 2005
>>On Thursday 29 September 2005 22:26, Alan G wrote:
>>> string -> function mapping directly.
>>> Its not usually a very useful thing to do
>This is precisely how shared libraries under linux and IIRC DLLs in
>windows work. cf dlopen, dysym in C.
No, its completely different. These are not done at the language
level but are implemented in the OS using an explicit mapoping
table built as part of the shared library creation process. That is
the language builds a dictionary of the string-function mapping.
It is not a feature of any of the languages used for building the
>># nm libpython2.4.so|head -20
>> U abort@@GLIBC_2.0
>>000dfea0 d abs_doc
>>0001fcf0 t abstract_get_bases
>>0001fe20 t abstract_issubclass
Yres but those names are not typed in as strings to call
the functions rather they are uised by the programmer
to access the functions through the library.
>>Obviously, ctypes does much the same thing.
but again by using/building mapping tables, ctypes is written
in C and Python neither of which provides a string-function
mapping. And ctypes is not exactly a commmon application type!
>> from ctypes import *
>> libc = cdll.LoadLibrary("/lib/libc.so.6")
>> sched_yield = libc.sched_yield
>> except ImportError:
>> import functions as libc
>> sched_yield = getattr(libc, "sched_yield")
>> # this is of course effectively
>> # sched_yield = libc.sched_yield
Yes, but getattr is simply looking up a dictionary which had
to be built by ctypes to start with - which is what the OP didn't
want to do... My argument was not that this was something
you'd never want to do just that its not something normally
supported by languages because its an unusual thing
to do - developers are unusual people, they do unusual things :-)
And of course if you want to delve into the innards of Python
you can pretty much do what was requested using the builtin
dictyionary/module mechanisms, but its not a simple \
mechanism and not recommended for general applications use...
More information about the Tutor