Return by reference from coder.ceval - access to a C array?
6 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hi,
We have some legacy C which we would like to run using coder.ceval.
Inside the C function there is an array and we would like the access the data within that array. (More correctly in the function there is an array pointer, so something like this ...
void myFun() {
int a[5];
int *p;
p = &a[0];
}
we want the data that is referenced by p).
I've found this link... https://uk.mathworks.com/help/coder/ug/returning-multiple-values-from-c-functions.html
So, this seems to tell me that if I do something along these lines...
void myFun(*p) {
int a[5];
p = &a[0];
}
and then in Matlab, if I do something like this....
coder.ceval('myFun',coder.wref(val));
will I then end up with the values from the array 'a' neatly into a Matlab array 'val'? Is that how this works? This all seems a bit too good to be true and I feel I must have missed something.
So, if anyone has experience of doing this, any advice would be most welcome before I waste hours doing it wrong tomorrow...
(I guess I would welcome any 'ponters' - HurHur ;)
Cheers, Arwel
0 comentarios
Respuestas (1)
James Tursa
el 7 de Sept. de 2017
Editada: James Tursa
el 7 de Sept. de 2017
I'm not familiar with what you can do to tweak the Coder, but for sure you can't get at the memory you are trying to in the above code reliably:
int a[5];
The variable "a" is a local variable, which means the memory for it will come from the stack. Once the myFun function returns to the caller, this memory is no longer valid to access. That stack memory is being overwritten by other functions etc that use the stack. So even if you did manage to return a pointer to that memory back to the caller (e.g. like your second function above), it would not be reliable to use in the caller.
You might be able to get something similar to that second piece of code to work reliably if you make that automatic local variable static instead. E.g.,
static int a[5];
In this case the memory for "a" is not obtained from the stack, but lives throughout the life of the program.
But the code you show is incorrect. It should be something like this instead:
// in the caller
int *p;
myFun(&p);
// myFun code
void myFun(int **p) {
static int a[5];
*p = &a[0];
}
Of course, if you have only one pointer to return it could be like this:
// in the caller
int *p;
p = myFun();
// myFun code
int *myFun(void) {
static int a[5];
return &a[0];
}
Note that since "a" is static, there is only one "a" in memory. If the function myFun is called recursively, the same "a" will be used in all of the calls (unlike local variables which would get new memory allocated for them off of the stack for each call).
0 comentarios
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!