[cairo] What is the closure in stream output to file based surfaces for?

Uli Schlachter psychon at znc.in
Tue Jul 29 02:35:44 PDT 2014


Hi,

On 29.07.2014 11:03, David Weiß wrote:
> Hey,
> 
> I want to implement file output for a rendering application and want to use C++ file streams using the following callback write function:
> 
>     cairo_status_t cairo_write_func (void *closure, const unsigned char *data, unsigned int length)
>     {
>         try
>         {
>             const std::string s(data, length);
>             fout << s;
>             fout.flush();
>         }
>         catch (std::exception &e)
>         {
>             return CAIRO_STATUS_WRITE_ERROR;
>         }
> 
>         return CAIRO_STATUS_SUCCESS;
>     }
> 
> I just can't figure out what the closure is for.
> Can anyone explain the concept to me?

You pass in a closure argument to cairo. Cairo doesn't do anything with it, it
just passes it on to your callback function. So it is meant to be used to pass
some state to the callback.

> Is it comparable to variable capturing in C++11 closures?

I guess so, yeah.

> Could I just pass nullptr as I do not use it anyway?
[...]

Sure, if that works for you, you can do so.

The "C approach" for your above code would be to use the closure argument to
pass a pointer to fout to the callback function via cairo and use a
reinterpret_cast to use it in there.

Cheers,
Uli
-- 
Sent from my Game Boy.


More information about the cairo mailing list