What's the best way to pass structures into/out of C++ functions?

조회 수: 5 (최근 30일)
Dan Grant
Dan Grant 2017년 10월 2일
댓글: James Tursa 2020년 4월 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?

답변 (2개)

James Tursa
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?

Jan
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
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
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 CenterFile Exchange에서 Structures에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by