Skip to content Skip to sidebar Skip to footer

C, C++ Interface With Python

I have c++ code that has grown exponential. I have a number of variables (mostly Boolean) that need to be changed for each time I run my code (different running conditions). I have

Solution 1:

Use subprocess to execute your program from python.

import subprocess as sp
import shlex

defrun(cmdline):
  process = sp.Popen(shlex.split(cmdline), stdout=sp.PIPE, stderr=sp.PIPE)
  output, err = process.communicate()
  retcode = process.poll()
  return retcode, output, err

run('./a.out '+arg1+' '+arg2+' '+...)

Solution 2:

Interfacing between C/C++ and Python is heavily documented and there are several different approaches. However, if you're just setting values then it may be overkill to use Python, which is more geared toward customising large operations within your process by farming it off to the interpreter.

I would personally recommend researching an "ini" file method, either traditionally or by using XML, or even a lighter scripting language like Lua.

Solution 3:

You can use subprocess module to launch an executable with defined command-line arguments:

import subprocess

option1 = True
option2 = Frue
# ...
optionN = True

lstopt = ['path_to_cpp_executable', 
           option1,
           option2,
           ...
           optionN 
         ]
lstopt = [str(item) for item in lstopt] # because we need to pass strings

proc = subprocess.Popen(lstrun, close_fds = True)
stdoutdata, stderrdata = proc.communicate()

If you're using Python 2.7 or Python 3.2, then OrderedDict will make the code more readable:

from collections import OrderedDict
opts = OrderedDict([('option1', True),
                    ('option2', False), 
                   ]

lstopt = (['path_to_cpp_executable'] + 
          list(str(item) for item in opts.values())
         )

proc = subprocess.Popen(lstrun, close_fds = True)
stdoutdata, stderrdata = proc.communicate()

Solution 4:

With the ctypes module, you can call arbitrary C libraries.

Solution 5:

There are several ways for interfacing C and C++ code with Python:

Post a Comment for "C, C++ Interface With Python"