2

Would it be possible to have a C++ dll call Python scripts and at the same time, have a python script call functions in the C++ dll that created the python instance in the first place?

What library could I use? And if none, are there any best practices? Would it be the best to use shared memory for the communication or should I use some sort of service which is able to conduct things?

My target platform is Windows

hutsend
  • 31
  • 4
  • 4
    Check out [Boost Python](http://www.boost.org/doc/libs/1_53_0/libs/python/doc/index.html). – Some programmer dude Apr 03 '13 at 15:50
  • 1
    This is called [embedding Python](http://docs.python.org/2/extending/embedding.html) – Janne Karila Apr 03 '13 at 15:51
  • 1
    You might consider Cython, which makes the interface singificantly simpler than using the straight Python/C API and can also be used along with embedding. I'd post an answer but I have experience with this only on Linux ;). – FatalError Apr 03 '13 at 15:55
  • I see how embedding python can be used to call python functions from C++, but I want to call C++ functions from the python I embedded too. I this anyhow possible? – hutsend Apr 04 '13 at 09:38

1 Answers1

2

You can use an external library written in C/C++ in Python using the ctypes module. Beware though that C++ mangles function names, and ctypes can only use functions that are declared extern "C"! (see e.g. this question)

To call a Python script from C++ you have two options:

  • Start a new Python process with the script name as an argument. On windows you can e.g. use CreateProcess for this.
  • Embed Python in the C++ app as Janne Karila mentioned.

Note that these things don't have much to do with communication between programs.

A library doesn't really communicate because it's not a process. It just supplies functions and data for a process to use.

And you can start a process from another process without communication whatsoever between them.

To communicate between processes you use interprocess communication. The different methods of doing that on Windows are listed here.

Community
  • 1
  • 1
Roland Smith
  • 42,427
  • 3
  • 64
  • 94