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

4
  • How exactly do you want to call the C-functions? Which functions would these be? Are they available as Python-functions? Commented 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. Commented Jun 11, 2014 at 3:43
  • ...see this question for more details. Commented Jun 11, 2014 at 3:44
  • More details can be found here: Calling C/C++ from python? Commented Apr 28, 2016 at 5:05

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
@ThePathan: Don't forget to select your favorite answer by marking the to the left.
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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.