send data to workspace without using mxArray

1 ビュー (過去 30 日間)
Indhu Priyadharshini Govindasamy
Indhu Priyadharshini Govindasamy 2022 年 3 月 4 日
編集済み: Walter Roberson 2022 年 3 月 10 日
I want to send data to the matlab workspace using matlab engine api for C?
but without using mxArray and also i dont want to use memcpy
mxArray *T = NULL;
double time[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
T = mxCreateDoubleMatrix(1, 10, mxREAL);
memcpy(mxGetDoubles(T), time, 10*sizeof(double));
memcpy(mxGetPr(T), time, 10*sizeof(double));
engPutVariable(ep, "T", T);
this example is working fine but is there any other way to send data to workspace using engine api for C?

回答 (1 件)

Walter Roberson
Walter Roberson 2022 年 3 月 10 日
編集済み: Walter Roberson 2022 年 3 月 10 日
Is there another way using engine API for C?
Yes. You can construct a string that codes a MATLAB assignment, and use
However, there is no way using the Engine API for C to do something like just take &time and say "use this block" or "copy this block"
mxArrays are how MATLAB keeps track of variables; they are tracked in the MATLAB memory allocator, and reference counting happens automatically for them, and they are reclaimed when no longer in use.
You could write a helper function that accepted a target variable name, and a memory pointer, and a size, and an encoding of the data type, and the helper did the copying for you.
You want to avoid doing memcpy(), but something has to copy the memory, unless the pointer to the existing memory is carried around. But the pointer to the existing memory might, as in your example, be a pointer into the stack, which is not going to be valid very long. Perhaps "you" know that the pointer is to malloc() or alloc() memory, but MATLAB has to assume that you might free() .
Suppose further that you did some kind of dynamic memory allocation, so you know that the memory block is not just going to disappear. Okay, now suppose the variable gets used a bit at the MATLAB level, and eventually it gets to the point where MATLAB knows it does not need the content anymore (for example the variable is overwritten.) Now what? There is no engHeresYourMemoryBack callback -- C doesn't even have callbacks as such. So to make it work, at the time you put the variable using the no-copy version, you would also have to give the pointer to a function to handle the fact that MATLAB no longer wants the memory. Possible, I guess, but certainly not what was implemented.


Find more on MATLAB Compiler in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by