What's the best way to pass structures into/out of C++ functions?
5 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
James Tursa
2017-10-2
编辑:James Tursa
2017-10-2
"... 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 个评论
Jan
2017-10-2
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 个评论
Royi Avital
2020-4-29
Is there an example of a MEX file converting MATLAB's array os structs to array of structs in C?
James Tursa
2020-4-30
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!