Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab binding of a C++ library using SWIG

I am already using SWIG to port some C++ libraries in Python, and I am really impressed by the quality of the results. So I'd like to stick with SWIG..

Recently somebody asked me for a Matlab port. Such a idea was actually already in my todolist.. but each time I was googling for that I didn't find nothing enough stable and easy to maintain (also because of my low skills with Matlab and its couple of ways to call C/C++ code).

From my understanding, there is an unmaintained and scarcely documented way to do this in the main branch, and many other attempts on such a direction that did not reach enough maturity to become part of the main branch: link. I'd like to be cross-platform thus I don't think that the COM way may be the solution for me.

However, this time I found that there is a branch that looks quite promising: link Did somebody already test this solution? In case, a simple working example that calls the ported C++ code from Matlab would be very helpful..

EDIT 1: I have removed any reference to C++11

EDIT 2: The matlab branch (cited in the answers) is currently in evaluation to be merged with the swig master (see: https://github.com/jaeandersson/swig/issues/72 and https://sourceforge.net/p/swig/mailman/message/35209729/ )

like image 381
gmas80 Avatar asked Oct 30 '14 23:10

gmas80


3 Answers

Since I am part of the current effort of implementing a MATLAB module for SWIG (which I wrote about in the mail you linked), I could provide a bit of background and report on the status as November 2014.

There have been several efforts to implement a MATLAB module for SWIG, using a variety of different approaches. As of today (November 2014), none of them have yet been successful in the sense of being incorporated into the master branch of SWIG (we hope to change that though in a not too distant future, see below).

Like you, I am using SWIG to port a C++ project (called CasADi) to Python and have been following developments of MATLAB support in SWIG for a couple of years now as this would be very useful for our project. After an effort that I was somewhat involved in failed to get past the proof-of-concept stage, I decided to give it a shot myself. In April this year (2014), I started coding and it went much smoother than I had expected. After about 2 weeks of coding, I already had the core functionality implemented (wrapping functions, classes and so on), which I posted to the SWIG community. I was happy to see a lot of positive response from the SWIG list and even more happy to see that people like Kris (see his answer) joining the effort and making great contributions.

The state of the module right now is that it has most functionality implemented and has used successfully for CasADi and other projects. For me, it demonstrates clearly that the chosen approach is the right one even if there is some work left to be done before the module is stable and documented. I hope to be able to make another push and actually manage to bring the SWIG module to a state where it can be incorporated into SWIG's master branch. But that depends on if/when I manage to secure funding to work on this. I'm confident that it could happen quite soon however.

Finally, your question mentions C++11. This is really a quite separate problem from the work on the MATLAB module. The stuff involving C++11 are mostly taken care of in SWIG in a matter which is independent of which language you're outputting to. So consult the C++11 support in SWIG in general.

like image 156
Joel Avatar answered Nov 10 '22 02:11

Joel


As you've found, there has been some recent activity for SWIG and MATLAB. This was started by Joel Andersson (building on previous efforts) and I've since then helped. We're both out-of-time, but did get it to work to a reasonable state. A few people have used it already to wrap "production" C++ code. Sadly, we don't have an easy TODO list anywhere, but check conversations on the swig-devel list.

Using this from matlab is quite easy. You can find examples in swig/Doc/Examples/matlab/. The test-suite has a few more of them.

For building simple examples, you can just run swig to generate the C++ mex file, and then from matlab do

mex yourModuleWrap.cxx

For more complicated stuff, you'll have to add your own library to the mex file. On the swig-devel list, you'll also find sample files for using CMake.

HTH

Kris

like image 4
krthie Avatar answered Nov 10 '22 00:11

krthie


I too have helped a bit with matlab integration with swig - though primarily as a tester. You can follow the instructions to interface my library (CoolProp) using SWIG following the instructions at: http://www.coolprop.dreamhosters.com:8010/sphinx/

Roughly the process is this:

  1. Compile a version of swig that includes the matlab support. There is a build script here: https://github.com/CoolProp/CoolProp/blob/master/dev/scripts/build_swig_matlab.py
  2. Using this special swig version, compile just like normal. We use CMake, so a rough snippet to make everything play nicely together is something like:

```

if (COOLPROP_MATLAB_SWIG_MODULE)

  # Must have SWIG
  FIND_PACKAGE(SWIG REQUIRED)
  INCLUDE(${SWIG_USE_FILE})

  find_package(Matlab REQUIRED)

  IF(MATLAB_FOUND)
      message(STATUS "MATLAB Found, MATLAB MEX will be compiled.")
  ELSE(MATLAB_FOUND)
      MESSAGE("MATLAB not found...nothing will be built.")
  ENDIF(MATLAB_FOUND)

  set(I_FILE "${CMAKE_SOURCE_DIR}/src/CoolProp.i")

  list (APPEND APP_SOURCES ${CMAKE_SOURCE_DIR}/wrappers/MATLAB/Matlabdef.def) # To export mexFunction

  SET_SOURCE_FILES_PROPERTIES(${I_FILE} PROPERTIES CPLUSPLUS ON)

  SWIG_ADD_MODULE(CoolPropMATLAB_wrap matlab ${I_FILE} ${APP_SOURCES})
  SWIG_LINK_LIBRARIES(CoolPropMATLAB_wrap ${MATLAB_LIBRARIES})

  add_definitions(/DMATLAB_MEX_FILE) #define matlab macros
  add_definitions(/DMX_COMPAT_32)

  add_custom_command(TARGET CoolPropMATLAB_wrap
                     POST_BUILD
                     COMMAND 7z a "+CoolProp.7z" "+CoolProp"
                     WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}")

  if(WIN32) # 32-bit or 64-bit mex
    if (CMAKE_CL_64)
        SET_TARGET_PROPERTIES(CoolPropMATLAB_wrap PROPERTIES PREFIX "" SUFFIX .mexw64)
    else()
        SET_TARGET_PROPERTIES(CoolPropMATLAB_wrap PROPERTIES SUFFIX .mexw32)
    endif()
  else()
    if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
        if (${BITNESS} EQUAL "32")
            SET_TARGET_PROPERTIES(CoolPropMATLAB_wrap PROPERTIES PREFIX "" SUFFIX .mexmaci32 PREFIX "")
        elseif((${BITNESS} EQUAL "64"))
            SET_TARGET_PROPERTIES(CoolPropMATLAB_wrap PROPERTIES PREFIX "" SUFFIX .mexmaci64 PREFIX "")
        endif()
    else()
        if (CMAKE_SIZEOF_VOID_P MATCHES "8")
            SET_TARGET_PROPERTIES(CoolPropMATLAB_wrap PROPERTIES PREFIX "" SUFFIX .mexa64 PREFIX "")
        else()
            SET_TARGET_PROPERTIES(CoolPropMATLAB_wrap PROPERTIES PREFIX "" SUFFIX .mexglx PREFIX "")
        endif()
    endif()
  endif()
  add_dependencies (CoolPropMATLAB_wrap generate_headers)
  install (FILES ${CMAKE_CURRENT_BINARY_DIR}/+CoolProp.7z DESTINATION ${CMAKE_INSTALL_PREFIX}/MATLAB)
  install (TARGETS CoolPropMATLAB_wrap DESTINATION ${CMAKE_INSTALL_PREFIX}/MATLAB)
endif()

```

  1. Load the compiled module into MATLAB
like image 4
ibell Avatar answered Nov 10 '22 01:11

ibell