Question

Looking at the OpenCL header file I see:

typedef struct _cl_context * cl_context;

I understand that cl_context is a pointer to a forward declared struct _cl_context.

From the perspective of a library designer, what are the advantages to doing this over:

typedef struct _cl_context cl_context;

Is it just so the API calls can take cl_context instead of cl_context*? But if so, why not just do:

typedef void *cl_context;
Was it helpful?

Solution

This is a typesafe way of building APIs, without exposing the internals of a type (which are implementation details).

typedef struct _cl_context* cl_context;

Doing this allows you to define the API using the type cl_context, without defining the struct _cl_context anywhere in the header files. It is clear to all that the functions take this type (a pointer) as an argument, but the user is not burdened with the details of struct _cl_context. The struct can be defined elsewhere (in the .c file or a private header).

The other approach you mention is:

typedef void* cl_context;

This is used as well many places. But requires typecasting in the code all over the place, before the argument can be interpreted. And it is not typesafe. The user can pass in any pointer as the argument, and the compiler will accept it - which is not a good thing. using the real type ensures some safety in terms of arguments being passed back and forth.

OTHER TIPS

In C, when you declare a struct like:

struct foo { };

To declare an instance of this struct, you would say:

struct foo f;

Therefore C programmers tend to declare structs like:

typedef struct foo { } foo;

As in, foo is a typedef for struct foo

This requirement is gone for C++.

I don't think that typedef struct cl_context; compiles. Maybe you meant typedef struct _cl_context cl_context;?

Is it just so the API calls can take cl_context instead of cl_context*?

That typedef takes care of both that and eliminating the need to prepend your type declarations with struct.

You would certainly not want to use typedef void *cl_context; because then you lose type safety.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top