Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a list through Python to C++

So I have a Python program that's finding .txt file directories and then passing those directories as a list(I believe) to my C++ program. The problem I am having is that I am not sure how to pass the list to C++ properly. I have used :

subprocess.call(["path for C++ executable"] + file_list)

where file_list is the [] of txt file directories.

My arguments that my C++ code accepts are:

 int main (int argc, string argv[])

Is this correct or should I be using a vector? When I do use this as my argument and try to print out the list I get the directory of my executable, the list, and then smiley faces, symbols, and then the program crashes.

Any suggestions? My main point that I am trying to find out is the proper syntax of utilizing subprocess.call. Any help would be appreciated! thanks!

like image 464
jnorris4118 Avatar asked Jul 18 '14 17:07

jnorris4118


1 Answers

Another option is to use cython, (not a direct answer). Here is a simple complete example:

Suppose you have the following files:

cython_file.cpp python_file.py setup.py sum_my_vector.cpp sum_my_vector.h

setup.py

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

ext_modules = [Extension(
    name="cython_file", 
    sources=["cython_file.pyx", "sum_my_vector.cpp"],
    extra_compile_args=["-std=c++11"], 
    language="c++",
    )]

setup(
    name = 'cython_file',
    cmdclass = {'build_ext': build_ext},
    ext_modules = ext_modules,
    )

cython_file.pyx

from libcpp.vector cimport vector

cdef extern from "sum_my_vector.h":
    int sum_my_vector(vector[int] my_vector)

def sum_my_vector_cpp(my_list):
    cdef vector[int] my_vector = my_list
    return sum_my_vector(my_vector)

sum_my_vector.cpp

#include <iostream>
#include <vector>
#include "sum_my_vector.h"

using namespace::std;

int sum_my_vector(vector<int> my_vector)
{
  int my_sum = 0;
  for (auto iv = my_vector.begin(); iv != my_vector.end(); iv++)       
      my_sum += *iv;

  return my_sum;
}

sum_my_vector.h

#ifndef SUM_MY_VECTOR
#define SUM_MY_VECTOR

using namespace::std;

int sum_my_vector(vector<int> my_vector);

#endif

python_file.py

from cython_file import sum_my_vector_cpp

print sum_my_vector_cpp([1,2,3,5])

Now run

python setup.py build_ext --inplace

and the you can run the python file

python python_file.py
11
like image 119
Akavall Avatar answered Nov 02 '22 19:11

Akavall