2

I have a source code written in cpp that I want to compile and be readable in Python. Python must give 2 filenames as input and retrieve a matrix and a vector as output. If I had to do it in C/C++ I'd use 2 chars and 2 pointers but I don't know how a compiled C/C++ program can be seen for Python language.

I hope that someone can help me. Thank you very much.

Nicholas
  • 1,915
  • 31
  • 55
  • You could do it with `ctypes` or a Python extension. The former would probably be quicker in terms of development. You build you C++ code into a DLL and export a single function. Read the ctypes documentation to learn how to get at it from Python. – David Heffernan Feb 18 '12 at 17:21
  • 3
    The answers to [this stackoverflow question](http://stackoverflow.com/questions/145270/calling-c-c-from-python) may be useful. – DSM Feb 18 '12 at 17:23
  • Thank you very much for the link but I have some issues on compile as a shared library. How can I do on Mac OS? – Nicholas Feb 19 '12 at 11:39

1 Answers1

1

Try using Swig to generate the glue code necessary to call C/C++ code from Python. It's easier than writing the code yourself.

Borealid
  • 95,191
  • 9
  • 106
  • 122
  • Thanks for the tip. I've installed swig on linux and it works perfectly, however on mac os I have some issues using the command `ld -shared` it says that it doesn't recognize `-shared`. How can I fix that? – Nicholas Feb 19 '12 at 11:33
  • @Nicholas Why are you running `ld` by hand? You should do your linking with `gcc` or `g++`. – Borealid Feb 19 '12 at 15:45
  • because I've found that on some website but it doesn't work on mac. Do you have any idea how to use `gcc` or `g++` I don't know all the possible options. I'm a newbie – Nicholas Feb 19 '12 at 16:32
  • @Nicholas The general procedure is something like this: run `g++ -c -fPIC mylib_wrap.cxx -o mylib_wrap.os` to *compile* the code (note the `-c`), then `g++ -shared -o libmylib.so mylib_wrap.os` to *link*. But I can't really give you a full guide here; there's plenty of information on the Internet. – Borealid Feb 19 '12 at 16:58