What's the best way to pass structures into/out of C++ functions?
5 views (last 30 days)
Show older comments
I have a C++ function (class method) that accepts a struct as input and passes a struct as output. I have a mex function that calls it. Ideally, I could pass in/out the structs directly to the mex function, but I don't see a good way to do that. The method in https://www.mathworks.com/help/matlab/matlab_external/passing-structures-and-cell-arrays.html is complex and also doesn't call a C++ function. Instead, I wrote a wrapper m-function that decomposes the strut to its component inputs, then reconstructs it on the back end, which isn't ideal either. What's the best way to pass a struct from Matlab into/out of a C++ function?
0 Comments
Answers (2)
James Tursa
on 2 Oct 2017
Edited: James Tursa
on 2 Oct 2017
"... decomposes the strut to its component inputs, then reconstructs it on the back end, which isn't ideal either ..."
If you want to work with the struct contents on the MATLAB side and the mex side as structs, that's pretty much what you have to do since the storage mechanisms for the data are different on both sides.
On the mex side, are you modifying the input data, or just using it as read-only data?
0 Comments
Jan
on 2 Oct 2017
Why do you think that the wrapper is "not ideal". Either the Matlab struct is converted to a list of variables by an M-function, provided as input to the Mex function, which creates the C struct from the data. Or you convert the Matlab struct to the C struct inside the Mex function. The first method might be more convenient, the second faster. So it matters if you call the function dozens or millions of times.
2 Comments
Royi Avital
on 29 Apr 2020
Is there an example of a MEX file converting MATLAB's array os structs to array of structs in C?
James Tursa
on 30 Apr 2020
Not generically. The C compiler needs to know what the struct contents are exactly at the time of compile. It can't create them dynamically on the fly at runtime when you pass in an arbitrary struct. You could work with pointers and pointers-to-pointers to kind-of simulate a dynamic structure on the C side, and keep track of what they are off to the side, but that's not the same thing as what I think you are asking.
See Also
Categories
Find more on Structures in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!