简体   繁体   中英

Correct way to return a matrix from a function

I have a function that computes and "create" a matrix. My function works well when it is inlined, but when I try to put the code into a function, I have trouble getting back the result matrix.

I want my function call to be like this :

CvMat projectionResult;
project_on_subspace(&projectionResult);
cvShowImage("test", &projectionResult );

(Eventually using *CvMat instead of `CvMat)

What I did was the following :

void project_on_subspace(CvMat * source)
{
source = cvCreateMat( feature_positions[feature_number].height, feature_positions[feature_number].width, CV_32FC1 );    

//some more code
}

But the cvCreateMa t function changes the value of the source pointer, so when I return from the function, the projectionResult matrix is not initialized.

I am aware this is a really easy question, but I don't really understand how to make this work? Is it possible to do it without changing the function prototype, or do I need to to change it to a **CvMat instead of a *CvMat ?

Edit : I'd prefer to return my result using in an argument pointer, rather than using a "return" statement, but both are fine.

CvMat * source means that you cannot change the address that source points to, but can change the contents of source . (Note that you can change it, it just won't change for the caller). If you need to be able to change where source points to you need to add another level of indirection making CvMat ** source which would then allow you to change *source and have it effect the calling method.

Do this instead (assuming cvCreateMat does not return a pointer to a cvCreateMat):

void project_on_subspace(cvMat **source)
{
    *source = cvCreateMat(etc...);
    // etc...

And call it like:

CvMat *projectionResult;
project_on_surface(&projectionResult);

Don't forget to deallocate the projectionResult in due time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM