How to modify a TypedArray in a structure without modifying the underlying pointer in a mex file?
이전 댓글 표시
I have a mex file which receives a structure which has several fields as input and returns the same structure. One of the fields is a 2D double array.
I can read the data on the specific field, cast is to a TypedArrayRef<double> and modify it. But everytime I look at the structure address behind data (using format debug) in successive executions of the MEX file, the pointer to the array changes. Why is this?
I am following this example: https://de.mathworks.com/help/matlab/matlab_external/avoid-copies-of-large-arrays.html
Does this mean the data is being copied? I want to avoid copying the data.
댓글 수: 3
James Tursa
2022년 1월 31일
편집: James Tursa
2022년 1월 31일
We need to see your actual code before we can offer specific advice. In general, however, it is not possible for a mex routine to take inputs and modify them without deep data copies using only the official API functions. You will be forced to deep copy your data with API functions or use unofficial hacks (with potential unwanted side effects) if you insist on avoiding deep data copies.
Simon Müller
2022년 1월 31일
편집: Walter Roberson
2022년 1월 31일
Simon Müller
2022년 2월 11일
답변 (1개)
Karan Singh
2024년 1월 30일
Hi Simon,
The MATLAB Data API, which you're using in the provided C++ MEX example, is designed to be safe and to prevent accidental misuse of memory. When you pass data from MATLAB to a MEX function, MATLAB uses a copy-on-write strategy. This means that the data is not physically copied until you try to modify it. When you access the data in a read-only fashion, you are looking at the original data. However, once you modify the data, MATLAB will create a copy of the data to preserve the original data's integrity.
In the example you've provided, you're modifying the elements of the array with this loop:
for (auto& elem : largeArray) {
if (elem < 0) {
elem = 0;
}
}
Hope this clarifies the doubt!
카테고리
도움말 센터 및 File Exchange에서 Write C++ Functions Callable from MATLAB (MEX Files)에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!