crystal-lang / crystal-book

Crystal reference with language specification, manuals and learning materials
https://crystal-lang.org/reference
Other
395 stars 249 forks source link

elaboration concerning opaque types? #70

Open rfrancis opened 7 years ago

rfrancis commented 7 years ago

In crystal-book/syntax_and_semantics/c_bindings/type.md one finds the following note:

Thus, a type declaration is useful for opaque types that are created by the C library you are wrapping. An example of this is the C FILE type, which you can obtain with fopen.

Any chance of some elaboration or clarification on that? I ran against this while (sigh) trying to make use of the OpenLDAP library, which has an opaque LDAP struct, and... I had and have no idea how to deal with that, despite this note. Just me?

ysbaddaden commented 7 years ago

Opaque C types can be represented in Crystal as:

lib MyLib
  type MyStruct = Void*
end

The C type can either be opaque (typedef void *my_struct) or be a defined struct, that doesn't matter: it's a pointer to some memory; the C library created it, knows what it is and how to deal with it. We don't care in Crystal, we just need the pointer.

The advantage of type over a simple alias, is that this will restrict the pointer type in Crystal, thus apply its type system. An alias would mean that any Void* pointer would be accepted which is wrong.

Maybe the documentation could be expanded a little if this wasn't obvious.