[C++-sig] detecting if a function is written in python or C++

pbarbier at cirad.fr pbarbier at cirad.fr
Thu Jan 12 10:39:03 CET 2006


Hello,

well, it is not specific to C++, but you will find that information in the
module where the function is defined. And the simplest way to get the
information is with the module "imp". So let suppose you got the function object
you want to test as the variable "fct" :

>>> imp.find_module(fct.__mofule__)[2]
('.so', 'rb', 3)

... the last number is the one one interest to you !
imp defines constant to know what it is. The constants are :
PY_SOURCE   (=1)
PY_COMPILED (=2)
C_EXTENSION (=3)

... if the value is 3 it means it's a C extension.

Hope this help !

Pierre

En réponse à Mathieu Lacage <Mathieu.Lacage at sophia.inria.fr>:

> hi,
> 
> I would like to be able to detect if the function/method I am calling
> from python is implemented as python or as c++ code in a boost python
> wrapper. Is this possible in a simple way ? The "inspect" python module
> does not seem to contain any reference to this sort of information.
> 
> A use case for this would be the following python code where the Event
> class is a c++ wrapper which calls back into the python "notify" method
> and whenre CppEvent is a c++ wrapper which calls back into a c++
> method.
> 
> class __MyEvent__(Event):
>     def set_callback (self, function, *args):
>         self.__function_ = function;
>         self.__args_ = args;
>     def notify (self):
>         self.__function_ (*self.__args_);
> 
> def make_event(function, *args):
>     #if function is python code, do this:
>         ev = __MyEvent__ ();
>         ev.set_callback (function, *args);
>     # otherwise, do something smarter to make the c++ 
>     # Event::notify method call directly in the c++ function 
>     # rather than go through the __MyEvent__.notify method 
>     # and then back to the c++ function.
>         ev = CppEvent ();
>         ev.set_callback (function, *args);
>     return ev
> 
> Mathieu
> -- 
> 
> _______________________________________________
> C++-sig mailing list
> C++-sig at python.org
> http://mail.python.org/mailman/listinfo/c++-sig
> 




More information about the Cplusplus-sig mailing list