1

I have created a Python wrapper around a C++ program using SWIG on Linux. The structure of the main function of the C++ program is like this:

MyProg.cpp

int main (int argc, char *argv[]) 
{
   ...
   ...
   ...
}

In other words, it takes a number of arguments from the command line (e.g. arg1, arg2) and uses those values during the execution:

$ g++ MyProg.cpp -o MyProg.x
$ MyProg.x arg1 arg2 ...

I created the python wrapper using the following SWIG commands:

$ swig -c++ -python MyProg.i
$ g++ -fpic -c MyProg.cpp -I/usr/include/python3.6 -I/usr/include -I/usr/include/x86_64-linux-gnu
$ gcc -shared MyProg_wrap.o MyProg.o -o _MyProg.so -lstdc++

where the file MyProg.i has the following:

MyProg.i

%module MyProg

%{
int main (int argc, char *argv[]);
%}

int main (int argc, char *argv[]);

My question is:

How do I capture the command line argument bit in the Python wrapper? I have tried passing the arguments inside brackets as shown below, but it does not work, as you can see:

$ python3
Python 3.6.9
[GCC 8.3.0] on linux
>>> import MyProg
>>> MyProg.main("arg1 arg2")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: main() missing 1 required positional argument: 'argv'
>>>

Is there an easy way I can reproduce the original C++ program functionality (i.e. passing command line arguments) in the Python wrapper too?

  • Why not just [start the C++ programme from within python](https://stackoverflow.com/questions/89228/calling-an-external-command-from-python)? – Aconcagua Jan 15 '20 at 18:16
  • @Aconcagua That's not a suitable option for me, I'm afraid. I have only given a simplified version of the problem. In actual fact the C++ project is quite large with many files and I need a proper Python wrapper, so that the C++ program appears as a proper Python3 module. – Curious Leo Jan 15 '20 at 19:04
  • 2
    My answer to this question should cover it I think: https://stackoverflow.com/a/11646101/168175. You probably don't want to call the function `main` though as that's a somewhat special function in C++ or C programs though. – Flexo Jan 15 '20 at 22:22
  • What happen if you call main as ``` .main(3, ["myprog", "arg1", "arg2"]) ``` ? BTW to automatically convert a single Python input argument to several C you need a SWIG %typemap(in) (int, char*[]) { ... } – Mike Jan 16 '20 at 00:28
  • @Flexo Wonderful! That worked, thanks. Would like to mark your comment as the accepted solution, but not sure if that is possible. – Curious Leo Jan 18 '20 at 19:15

0 Answers0