How to cast OpenCV cv::Mat as NULL pointer?

I am using a 3rd party SDK in my project which accepts NULL pointer for setting user specific metadata. But my metadata is in cv::Mat format thus I need to cast the cv::Mat as NULL pointer as shown here:

void *set_metadata_ptr(cv::Mat frame)

  cv::Mat *user_metadata = new cv::Mat();


  return (void *)user_metadata;

void foo() 
UserMeta *user_meta = NULL;
user_meta->user_meta_data = (void *)set_metadata_ptr(frame);

This works good, but many of the OpenCV power users discourage using pointers with cv::Mat as cv::Mat has smart pointer itself. I wonder is there any better way to cast the cv::Mat as NULL pointer in my case?

which is ? can you point us to the API used here ?
why do you assume, a pointer to cv::Mat is expected on the “other side” ?
what about the memleak above ? who’s responsible to delete it ? pointer ownership ?
what are you trying to achieve here ?
(this seriously looks like an XY problem)

no, your code is not showing that

also, totally wrong here:

(trying to access a member on a NULL pointer)



Yes, Mat uses smart pointers for the image data (or any matrix data). So, it is recommended to pass Mat as arguments and no as pointers, because the actual copied object is very small: the image itself is not copied.

But, if your 3rd party library ask for a Mat*, it seems there is no alternative.

i bet a 20, it’s NOT asking for a cv::Mat* in the 1st place
(and that the op is just terribly confused, about what is actually required here)

The 3rd party library is designed for handling gchar data, but I am providing it a pointer to cv::Mat and it works as shown in the code snipped. But I am asking for suggestions if its a good idea or not.

again, link ? (this wont go anywhere without)

gchar data containing what, exactly ?

this IS clearly an XY problem
@Abu_Amran – please start all over.

  • show us the api you try to use
  • tell us, what you try to do with it
  • throw away all of your current code
  • learn about “POD” objects (and casts !), and why cv::Mat is NOT one

please answer my questions above

You won, he’s not asking for Mat*.
My bad, I loose.
Here is your twenty:

I agree with @berak, it’s all about ownership and preventing memory leak and dangling pointer.

You don’t even need to copy the original Mat, as long it survive the API use of its data.

And if it doesn’t, I believe it is cleaner code if you just copy the data in the heap (new array of char) instead of copying to another Mat. And you remain responsible for deleting it when no longer in use.