import "zlib.h" reads the header (cc -E + a small C declaration parser), links via pkg-config or link "name", and builds .c/.cpp files next to the program. C structs become Dino structs, pointers become pointer types (nil = NULL), T* parameters take variables or lists. Adds dino header, editor completion/hover for C names, docs chapter 13, a raylib example, and tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
305 lines
8.7 KiB
Markdown
305 lines
8.7 KiB
Markdown
# 13. C and C++ libraries
|
|
|
|
A huge amount of useful code is written in C: graphics (raylib, SDL), compression (zlib),
|
|
databases (SQLite), and the C library that comes with every system. Dino can use it
|
|
directly. You don't write any declarations: Dino reads the library's **header file** (the
|
|
`.h` file that lists what the library has) and works out the rest.
|
|
|
|
## Importing a header
|
|
|
|
Put the header's name in quotes. Its functions, types and constants are then used with the
|
|
header's name in front, the same way as your own files (`import utils` gives `utils.name`).
|
|
|
|
```dino
|
|
import "string.h"
|
|
import "stdlib.h"
|
|
|
|
func main() {
|
|
print(string.strlen("hello"))
|
|
print(stdlib.abs(-7), stdlib.atoi("42") + 1)
|
|
}
|
|
```
|
|
```text
|
|
5
|
|
7 43
|
|
```
|
|
|
|
The name in front is the file name without `.h`: `"zlib.h"` gives `zlib`, `"SDL2/SDL.h"`
|
|
gives `SDL`, `"my-lib.h"` gives `my_lib`. To choose another one, write it before the quotes:
|
|
`import z "zlib.h"` gives `z.crc32(...)`.
|
|
|
|
## Picking a few names
|
|
|
|
When you only want some things from a header, list them in braces. Those names are then
|
|
used **without** a prefix, and nothing else from the header is visible:
|
|
|
|
```dino
|
|
import "math.h" { cbrt, hypot }
|
|
|
|
func main() {
|
|
print(cbrt(27.0), hypot(3.0, 4.0))
|
|
}
|
|
```
|
|
```text
|
|
3.0 5.0
|
|
```
|
|
|
|
(`math.h` is the C math library. Dino's own `import math` is usually nicer; this is just a
|
|
small example.)
|
|
|
|
## How C types look in Dino
|
|
|
|
| In C | In Dino |
|
|
|------|---------|
|
|
| `int`, `unsigned int`, `short`, ... | `i32`, `u32`, `i16`, ... |
|
|
| `long`, `long long`, `int64_t` | `int` |
|
|
| `size_t`, `unsigned long`, `uint64_t` | `u64` |
|
|
| `double` / `float` | `float` / `f32` |
|
|
| `char` | `i8` (you can pass a character like `'a'`) |
|
|
| `bool` | `bool` |
|
|
| `const char *` and `char *` | `string` |
|
|
| an `enum` | its values are constants (`i32`) |
|
|
| a `struct` with plain fields | a Dino struct: `raylib.Color{255, 0, 0, 255}` |
|
|
| any other pointer (`FILE *`, `SDL_Window *`) | a pointer type: `stdio.FILE`, `SDL.SDL_Window` |
|
|
| `NULL` | `nil` |
|
|
|
|
Numbers follow the usual Dino rule: a number written in the code fits any number type, but
|
|
a variable has to be converted, for example `i32(n)` when the C function takes an `int`.
|
|
|
|
Text works both ways: a Dino string is handed to C as a C string, and a C string that comes
|
|
back becomes a Dino string (a copy, so it stays valid).
|
|
|
|
## Pointers: things you only pass around
|
|
|
|
Many C libraries give you a pointer to something they manage, like an open file or a
|
|
window. In Dino you keep it in a variable, hand it back to the library, and compare it with
|
|
`nil` to see if it is missing:
|
|
|
|
```dino
|
|
import "stdio.h"
|
|
import os
|
|
|
|
func main() {
|
|
var f = stdio.fopen("/tmp/dino-hello.txt", "w")
|
|
if f == nil {
|
|
print("can't open the file")
|
|
return
|
|
}
|
|
stdio.fputs("hello from C\n", f)
|
|
stdio.fclose(f)
|
|
|
|
var text, err = os.read_file("/tmp/dino-hello.txt")
|
|
print(text.trim(), err)
|
|
}
|
|
```
|
|
```text
|
|
hello from C nil
|
|
```
|
|
|
|
The type can be written like any other: `var f: stdio.FILE` starts out as `nil`.
|
|
|
|
**Dino does not free C things for you.** Whatever the library opens or creates, close or
|
|
free it with the library's own function (`fclose`, `sqlite3_close`, `UnloadTexture`, ...).
|
|
|
|
## Functions that write into your variables
|
|
|
|
Some C functions give back extra results by writing into a variable you pass them (in C:
|
|
a pointer parameter like `double *out`). Pass a Dino **variable**, and the function changes
|
|
it. Pass a **list** where the C function wants room for several values (a buffer):
|
|
|
|
```dino
|
|
import "math.h" { modf }
|
|
import "string.h" { memset }
|
|
|
|
func main() {
|
|
var whole = 0.0
|
|
var frac = modf(3.75, whole) // modf writes the whole part into `whole`
|
|
print(frac, whole)
|
|
|
|
var buf: []u8 = [0, 0, 0]
|
|
memset(buf, 65, 3) // fills the list's items
|
|
print(buf)
|
|
}
|
|
```
|
|
```text
|
|
0.75 3.0
|
|
[65, 65, 65]
|
|
```
|
|
|
|
A list given to C must already have as many items as the function will write; the C
|
|
function can't make it longer.
|
|
|
|
The same goes for libraries that hand you a new pointer through a parameter (in C:
|
|
`sqlite3 **db`). Make a variable of that pointer type and pass it; afterwards it is set:
|
|
|
|
```text
|
|
var db: sqlite3.sqlite3
|
|
sqlite3.sqlite3_open("notes.db", db) // db is now open (or still nil if it failed)
|
|
```
|
|
|
|
## Constants
|
|
|
|
Values from `#define` and `enum` work like Dino constants: `stdio.EOF`, `zlib.Z_OK`,
|
|
`raylib.KEY_SPACE`. raylib's colours (`raylib.RED`, `raylib.RAYWHITE`) are struct constants
|
|
of type `raylib.Color`.
|
|
|
|
## Linking: where the library's code is
|
|
|
|
The header only describes a library; its code is in a library file that has to be linked
|
|
in. Dino asks the system (`pkg-config`) for that, so for most installed libraries
|
|
`import "raylib.h"` or `import "zlib.h"` is all you need. If a library isn't known to
|
|
`pkg-config`, name it yourself: for the file `libfoo.so`, write
|
|
|
|
```text
|
|
import "foo.h" link "foo"
|
|
```
|
|
|
|
If it is missing, building stops with a message that says so.
|
|
|
|
## A window with raylib
|
|
|
|
[raylib](https://www.raylib.com) is a simple library for games and graphics. With it
|
|
installed, this opens a window and draws a circle:
|
|
|
|
```dino
|
|
import "raylib.h"
|
|
|
|
func main() {
|
|
raylib.InitWindow(800, 450, "Hello from Dino")
|
|
raylib.SetTargetFPS(60)
|
|
var x: f32 = 400.0
|
|
for !raylib.WindowShouldClose() {
|
|
if raylib.IsKeyDown(raylib.KEY_RIGHT) { x += 4.0 }
|
|
if raylib.IsKeyDown(raylib.KEY_LEFT) { x -= 4.0 }
|
|
raylib.BeginDrawing()
|
|
raylib.ClearBackground(raylib.RAYWHITE)
|
|
raylib.DrawCircleV(raylib.Vector2{x, 225.0}, 40.0, raylib.MAROON)
|
|
raylib.DrawText("arrow keys move the ball", 10, 10, 20, raylib.DARKGRAY)
|
|
raylib.EndDrawing()
|
|
}
|
|
raylib.CloseWindow()
|
|
}
|
|
```
|
|
|
|
A bigger example with bouncing balls is in
|
|
[`examples/c/bounce.dino`](../examples/c/bounce.dino).
|
|
|
|
## Your own C code
|
|
|
|
Put a header and its `.c` file next to your program. `import "shapes.h"` reads the header,
|
|
and Dino compiles `shapes.c` and builds it into your program.
|
|
|
|
```c
|
|
// shapes.h
|
|
typedef struct { double w, h; } Size;
|
|
double area(Size s);
|
|
void grow(Size *s, double by);
|
|
```
|
|
|
|
```c
|
|
// shapes.c
|
|
#include "shapes.h"
|
|
double area(Size s) { return s.w * s.h; }
|
|
void grow(Size *s, double by) { s->w *= by; s->h *= by; }
|
|
```
|
|
|
|
```dino
|
|
import "shapes.h"
|
|
|
|
func main() {
|
|
var s = shapes.Size{2.0, 3.0}
|
|
shapes.grow(s, 10.0) // grow changes `s`
|
|
print(shapes.area(s), s.w)
|
|
}
|
|
```
|
|
```text
|
|
600.0 20.0
|
|
```
|
|
|
|
## C++
|
|
|
|
C++ code can't be called from C or Dino directly: C++ functions get scrambled ("mangled")
|
|
names when compiled, and classes and templates don't exist in C. The usual fix is a small
|
|
set of plain functions marked `extern "C"`. Write them in a `.cpp` file next to the header,
|
|
and Dino compiles it with your C++ compiler (`c++`) and links in the C++ library:
|
|
|
|
```c
|
|
// counter.h: plain C, also readable by C++
|
|
#ifdef __cplusplus
|
|
extern "C" {
|
|
#endif
|
|
typedef struct Counter Counter;
|
|
Counter *counter_new(void);
|
|
void counter_add(Counter *c, int n);
|
|
int counter_total(const Counter *c);
|
|
void counter_free(Counter *c);
|
|
#ifdef __cplusplus
|
|
}
|
|
#endif
|
|
```
|
|
|
|
```cpp
|
|
// counter.cpp: free to use any C++ inside
|
|
#include "counter.h"
|
|
#include <numeric>
|
|
#include <vector>
|
|
struct Counter { std::vector<int> items; };
|
|
extern "C" {
|
|
Counter *counter_new(void) { return new Counter{}; }
|
|
void counter_add(Counter *c, int n) { c->items.push_back(n); }
|
|
int counter_total(const Counter *c) { return std::accumulate(c->items.begin(), c->items.end(), 0); }
|
|
void counter_free(Counter *c) { delete c; }
|
|
}
|
|
```
|
|
|
|
```dino
|
|
import "counter.h"
|
|
|
|
func main() {
|
|
var c = counter.counter_new()
|
|
for i in 1..5 { counter.counter_add(c, i32(i)) }
|
|
print(counter.counter_total(c))
|
|
counter.counter_free(c)
|
|
}
|
|
```
|
|
```text
|
|
10
|
|
```
|
|
|
|
The same trick works for a big C++ library: wrap the few things you need in `extern "C"`
|
|
functions.
|
|
|
|
## Seeing what a header has
|
|
|
|
`dino header` lists everything Dino can use from a header, written as Dino. Add a word to
|
|
only see names that contain it:
|
|
|
|
```text
|
|
dino header zlib.h compress
|
|
```
|
|
```text
|
|
import "zlib.h" // use the names below as zlib.name
|
|
// builds with: -DWITH_GZFILEOP -lz
|
|
|
|
// functions
|
|
func compress(dest: []u8 or u8 variable, destLen: []u64 or u64 variable, source: []u8 or u8, sourceLen: u64): i32
|
|
...
|
|
```
|
|
|
|
In an editor with Dino support, completion after `zlib.` and hovering a name show the same.
|
|
|
|
## What doesn't work yet
|
|
|
|
Dino tells you when you call one of these, and why:
|
|
|
|
- functions with a variable number of arguments, like `printf`
|
|
- functions that take a callback (a function pointer)
|
|
- `union` types, and structs with arrays inside (you can still pass pointers to them)
|
|
- a list of structs where C wants several structs in a row
|
|
- C macros that take arguments (`#define MAX(a, b) ...`)
|
|
|
|
When you need one of these, write a small function in your own `.c` file that does the C
|
|
part, and call that from Dino.
|
|
|
|
Next: back to the [overview](README.md)
|