WARNING: THIS SITE IS A MIRROR OF GITHUB.COM / IT CANNOT LOGIN OR REGISTER ACCOUNTS / THE CONTENTS ARE PROVIDED AS-IS / THIS SITE ASSUMES NO RESPONSIBILITY FOR ANY DISPLAYED CONTENT OR LINKS / IF YOU FOUND SOMETHING MAY NOT GOOD FOR EVERYONE, CONTACT ADMIN AT ilovescratch@foxmail.com
Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions docs/syntax_and_semantics/c_bindings/fun.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,19 @@ end
```

NOTE: The C `char` type is `UInt8` in Crystal, so a `char*` or a `const char*` is `UInt8*`. The `Char` type in Crystal is a unicode codepoint so it is represented by four bytes, making it similar to an `Int32`, not to an `UInt8`. There's also the alias `LibC::Char` if in doubt.

## Top-level fun

A `fun` defined at the top-level namespace defines and exports a C function that can be called by external C code:

```crystal
fun sum(x : Int32, y : Int32) : Int32
x + y
end

sum(1, 2) # => 3
```

Like lib funs, all parameter and return types are mandatory, and only valid types in C bindings are permitted. Like regular Crystal defs, they have a body and can be called directly by other Crystal code.

Because Crystal programs are not meant to be used as shared libraries, top-level methods should be defined using the `def` keyword instead of `fun`. Exceptions are entry points used by the underlying operating system, such as the C `main` on most systems.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The "are not meant to be used as shared libraries" might be a bit strong. That applies mostly to stdlib which imposes restrictions on usefulness as a library. But this is the language specification, not stdlib.
I'd maybe tone that down a little bit.