2

I would like to write a CMakeLists.txt such that CMake writes a Visual Studio 2010 (64 bit) solution file to build a mex function for MATLAB R2011a (64 bit) from C++ code example.cxx.

  1. I do not want to use MATLAB's compiler wrapper mex but set up the Visual Studio solution file such that Visual C++ links the relevant MATLAB libraries.
  2. example.cxx has no dependencies except for the MATLAB libraries that are necessary for mex files.
  3. CMake 2.8.7 is set up correctly such that it uses the 64 bit generator for Visual Studio 2010.

The essence of what I am doing right now is

find_package(Matlab)
add_library(example STATIC example.cxx)
target_link_libraries(example ${MATLAB_LIBRARIES})

Neither the compiler nor the linker issues any errors. I install the output example.lib under the name example.mexw64 in a directory in MATLAB's path. When I call example from MATLAB, I get the error message

??? Invalid MEX-file
'C:\...\example.mexw64':
C:\...\example.mexw64 is not a valid Win32 application.

Any suggestions are welcome!

2 Answers2

3

I had the same problem and this link was very helpful (also serves as a nice example of how to use ITK in a MATLAB MEX file btw). I think for your case, you need to add the link flag "/export:mexFunction" to your CMakeLists.txt file. Example below:

PROJECT(example)
FIND_PACKAGE(Matlab REQUIRED)

INCLUDE_DIRECTORIES(${MATLAB_INCLUDE_DIR})

ADD_LIBRARY(example MODULE example.cpp)
ADD_DEFINITIONS(-DMATLAB_MEX_FILE)

# Needed for entry point.
SET_TARGET_PROPERTIES(example
PROPERTIES
LINK_FLAGS "/export:mexFunction"
)

# Change the dll extension to a mex extension.
set_target_properties(example PROPERTIES SUFFIX ".mexw64")

TARGET_LINK_LIBRARIES(example ${MATLAB_LIBRARIES})

Note that the FIND_PACKAGE(Matlab) doesn't seem to work all that well, so that may be a problem for some people. I had to get around it by hard-coding the MATLAB paths into CMakeLists.txt (not shown in this example).

Jer K
  • 885
  • 8
  • 11
0

Matlab mex files are dll`s not libs. Try making cmake (not an expert on that) create a dynamic librart، not static.

Tal Darom
  • 1,379
  • 1
  • 8
  • 26
  • I tried this. Now I get the error: `Mex file entry point is missing. Please check the (case-sensitive) spelling of mexFunction (for C MEX-files), or the (case-insensitive) spelling of MEXFUNCTION (for FORTRAN MEX-files). ??? Invalid MEX-file 'C:\...\example.mexw64': C:\...\example.mexw64 is not a valid Win32 application.` – Bernhard Anderson Apr 18 '12 at 22:17
  • When I specify the entry point explicitly in the Visual Studio solution file (how does one get CMake to do it in a platform-independent fashion?), I get this error message: `??? Invalid MEX-file 'C:\...\example.mexw64':` – Bernhard Anderson Apr 18 '12 at 22:24
  • your dll need to export the function mexFunction. Maybe it is not exported or not spelled correctly. – Tal Darom Apr 18 '12 at 22:55