0

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!!!

Haider
  • 341
  • 3
  • 18
  • How exactly do you want to call the C-functions? Which functions would these be? Are they available as Python-functions? – Schorsch Jun 11 '14 at 02: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 Jun 11 '14 at 03:43
  • ...see [this question](http://stackoverflow.com/questions/6848790/embed-a-function-from-a-matlab-mex-file-directly-in-python) for more details. – nneonneo Jun 11 '14 at 03:44
  • More details can be found here: [Calling C/C++ from python?](http://stackoverflow.com/questions/145270/calling-c-c-from-python) – Hackless Apr 28 '16 at 05:05

2 Answers2

1

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!

Noob Saibot
  • 4,573
  • 10
  • 36
  • 60
1

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).

nneonneo
  • 171,345
  • 36
  • 312
  • 383
  • Thanks for the reply!!! Searching around, it seems ctypes is the easiest way to start off. Also, I can import **ctypes** from within the ImageJ environment, which is important for my project (The project is to convert the Matlab program into an imageJ plugin). However, I have never built anything as a shared library. I may be asking you for help, if it gets too complicated. But Thanks for the help. It is very appreciated. – Haider Jun 11 '14 at 08:08
  • @ThePathan: Don't forget to select your favorite answer by marking the **✓** to the left. – Noob Saibot Jun 11 '14 at 16:12