CoffeeTableEspresso
CoffeeTableEspresso

Reputation: 2652

Incomplete type with size

I'm writing a C library, and have a struct that looks (roughly) like:

struct Obj {
    char tag,
    union { 
        int i,
        void *v
    } val
};

I do not want to expose the internals of this struct through the API, because users do not need to know the implementation and they could change in future versions. Users can interact with the struct via functions in the API.

I used incomplete types in the header for other, larger types in my API, which can only be accessed via pointer by the user. I do not want to restrict users to accessing Obj via pointer, as Obj will likely only be 16 bytes maximum.

I have not been able to use an incomplete type here, because I do not know of a way to expose only the size of the struct to users, without fields.

My question is: Is there a way to expose a type with size only in C (no knowledge of the fields in the struct given to user), some other hack to accomplish what I want, or should I implement this in some completely different way?

Please comment if I haven't provided enough details or anything is unclear.

Upvotes: 1

Views: 333

Answers (1)

nemequ
nemequ

Reputation: 17532

The standard pattern for this is to create a function which allocates the struct for the user:

struct Obj* obj_new(void) {
  return malloc(sizeof(struct Obj));
}

Then just leave the type as incomplete in your public header.

Of course, if you really want to expose only the size, you could just create a function which returns sizeof(struct Obj). Obviously people can misuse it (e.g., hardcoding the value into their code as an "optimization" to avoid calling that function), but that's not on you. It is something that is done occasionally, usually to help facilitate inheritance.

Upvotes: 1

Related Questions