I am currently working on a project to import a Matlab program to python for integration into ImageJ as a plugin. The program contains Mex files and the source code was written in C++. Is there a way to call the C++ functions without having to rewrite them in python. Thanks!!!
-
How exactly do you want to call the C-functions? Which functions would these be? Are they available as Python-functions?Schorsch– Schorsch2014-06-11 02:08:03 +00:00Commented Jun 11, 2014 at 2:08
-
1@ThePathan: You won't be able to call MEX functions directly from Python, I think. You'd need to have implementations of all the MATLAB MEX API functions, which seems impossible unless you are using MATLAB.nneonneo– nneonneo2014-06-11 03:43:38 +00:00Commented Jun 11, 2014 at 3:43
-
...see this question for more details.nneonneo– nneonneo2014-06-11 03:44:12 +00:00Commented Jun 11, 2014 at 3:44
-
More details can be found here: Calling C/C++ from python?Hackless– Hackless2016-04-28 05:05:33 +00:00Commented Apr 28, 2016 at 5:05
2 Answers
If you can build your program as a shared library, then you can use the ctypes foreign-function interface to call your functions.
This is often less work (and less complex) than wrapping the functions with Cython or writing your own C-API extension, but it is also more limited in what you can do. Therefore, I recommend starting with ctypes, and moving up to Cython if you find that ctypes doesn't suit your needs.
However, for simple libraries, ctypes will do just fine (I use it a lot).
2 Comments
Welcome to Stack Overflow!
You would need to wrap those C functions into python C extensions, through the Python C-API, for them to be callable from python; however, i can tell you from experience that the task can be a headache if you don't know what you're doing.
I would recommend checking out cython. It makes writing C extensions as easy as writing python code!