Reputation: 71
I have a program written in C++ with a web interface to for the purpose of RPC. I can call http://localhost/ListVariables
or http://localhost/RunFunction?var=1
and have the C code execute ListVariables or RunFunction. It works, but I'd rather not have to manage the web server in C/C++ when there are so many good Python web servers out there.
What I'm imagining is having the C program call into Python to start a web server on another thread (i.e. Tornado), return to C and then continue chugging along doing calculations. Then when the Python server receives a request on http://localhost/ListVariables
, it calls back into C and executes ListVariables on the already running process.
C -----> processing -----------> processing ------------> RPC: FuncA -------->
| ^ |
\---> Python Web Server ---------- Request for: FuncA --/ ... \-------->
^
browser: http://localhost/FuncA ---/
The project has the unfortunate caveat that the program must be started from C to begin with. After doing some research this seems to be a bit of a border case, since Python-->C and C-->Python can be done with Cython. However, I can't find many resources on C-->Python-->C, as most of the examples I've found describe linking to libraries and not to already-running processes. Is it possible to have Python call back into a running C program?
Upvotes: 2
Views: 930
Reputation: 5250
I personally really like the boost::python library for embedded python into c++ and dealing with data binding and callbacks between the two. http://www.boost.org/doc/libs/1_51_0/libs/python/doc/
That being said, what you're proposing sounds like a bit of a PITA. I've personally have had a lot of success using http://libevent.org/ to fulfill my embedded webserver needs. It handles all of the http server stuff for you, all you need to do is give it the urls you want to handle and a callback, put the event_base_loop
somewhere in your main loop (or in it's own thread if you'd rather), and away you go. That to me seems like it might be a lot easier than embedding python and dealing with passing data and data structures between the two.
Upvotes: 0
Reputation: 799100
Absolutely. Create a "fake" module in the C program injected into sys.modules
that the Python code can import and access as it would any other module.
Upvotes: 1