Share buffer between Matlab and dylib

4 views (last 30 days)
Qiulin
Qiulin on 9 Oct 2023
Answered: Rijuta on 16 Oct 2023
Using Matlab "calllib" function to interact with a c++ function on mac (c++ is compiled as dylib file on Mac).
Now I want to define a struct in matlab, so that I can pass it into the dylib and write into the struct in c++ and return it back to Matlab. Currently thinking about define a buffer and then send the address to c++ and write into the buffer but don't know how to implement it. Any ideas, examples or suggestions? Thank you!

Answers (1)

Rijuta
Rijuta on 16 Oct 2023
Hi Qiulin,
I understand that you want to pass a struct between MATLAB and C++ using a buffer.
Instead of directly passing the struct, you can create a buffer in MATLAB, pass the address of the buffer to the C++ function, and then read and write data to the buffer in both MATLAB and C++.
Below are the steps to do the same:
  1. Load the C++ library (dylib file) using the “loadlibrary” function in MATLAB.
  2. Define the size of the buffer. The size of the buffer should be large enough to accommodate all the fields of the struct.
  3. Create a buffer in MATLAB “libpointer” function to make a pointer object for use with shared C++ library.
  4. Call the C++ function using the “calllib” function in MATLAB.
  5. You can access the modified buffer data in MATLAB by accessing the “Value” property of the buffer pointer.
  6. Pass the buffer to your C++ function. Here, we can modify the buffer data by directly accessing the memory locations.
Kindly refer the documentations below for more details:
I hope this solves your query.

Products


Release

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!