2

I need to call InitGoogleLogging() when my C++ library is imported in Python. My C++ library uses Boost.Python.

How do I call functions when the library is imported?

1 Answer 1

6

There are no real "definitions" in python. Any code you put in a .py module is executed when you import it. It just happens to be that most of the time the code put in the package files is the "definiton" code like class or def. In practice, that code still gets executed, it just creates your class and function definitions as a result. Calling a function from the root namespace (indentation) in the module will cause it to get called as soon as the module is loaded.

Just put them into the __init__.py. See http://www.boost.org/doc/libs/1_45_0/libs/python/doc/tutorial/doc/html/python/techniques.html#python.extending_wrapped_objects_in_python where it talks about exporting your package with an alias and then flatning your namespace in init.py.

i.e. (this would be __init__.py in a a subdirectory named foo):

from _foo import *

InitGoogleLogging()

Another alternative is calling it directly from the C++ wrapper module:

BOOST_PYTHON_MODULE(foo)
{
    InitGoogleLogging();

    class_<Foo>("Foo")
        .def("bar", &bar)
    ;
}
Sign up to request clarification or add additional context in comments.

9 Comments

Thanks a lot. I like the second solution, but I need to get at argv. Does boost::python give me a way to get at argv? maybe I could call sys.argv[0]?
Do you mean argv for the application? If you do, then yes.
@aleksey: I do. How do I get sys.argv[0] from within my C++ code?
See boost.org/doc/libs/1_46_0/libs/python/doc/v2/exec.html. One comment I have is why do you insist on doing all this from C++ side? A lot of these things are a lot easier to do from Python. If you're worried about showing your source code, you can always distribute just the .pyc or .pyo files without the .py file...
Yes. It might make more sense to have a Python function that passes the necessary arguments to the C++ code, and use that in a module that imports your C++ code. That feels cleaner, and is definitely more flexible.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.