2025-07-12 12:43:17 -04:00
|
|
|
Codon can be called from C/C++ code by compiling to a
|
|
|
|
|
shared library that can be linked to a C/C++ application.
|
|
|
|
|
|
|
|
|
|
Codon functions can be made externally visible by annotating
|
|
|
|
|
them with `@export` decorator:
|
2022-07-26 16:08:42 -04:00
|
|
|
|
|
|
|
|
``` python
|
|
|
|
|
@export
|
|
|
|
|
def foo(n: int):
|
|
|
|
|
for i in range(n):
|
|
|
|
|
print(i * i)
|
|
|
|
|
return n * n
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
Note that only top-level, non-generic functions can be exported. Now we
|
|
|
|
|
can create a shared library containing `foo` (assuming source file
|
2025-07-12 12:43:17 -04:00
|
|
|
`foo.codon`):
|
2022-07-26 16:08:42 -04:00
|
|
|
|
|
|
|
|
``` bash
|
2023-05-23 17:59:26 -04:00
|
|
|
codon build --relocation-model=pic --lib -o libfoo.so foo.codon
|
2022-07-26 16:08:42 -04:00
|
|
|
```
|
|
|
|
|
|
2023-05-23 17:59:26 -04:00
|
|
|
Now we can call `foo` from a C program (if you're using C++, mark the
|
|
|
|
|
Codon function as `extern "C"`):
|
2022-07-26 16:08:42 -04:00
|
|
|
|
|
|
|
|
``` c
|
|
|
|
|
#include <stdint.h>
|
|
|
|
|
#include <stdio.h>
|
|
|
|
|
|
|
|
|
|
int64_t foo(int64_t);
|
2023-05-23 17:59:26 -04:00
|
|
|
// In C++, it would be:
|
|
|
|
|
// extern "C" int64_t foo(int64_t);
|
2022-07-26 16:08:42 -04:00
|
|
|
|
|
|
|
|
int main() {
|
|
|
|
|
printf("%llu\n", foo(10));
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
Compile:
|
|
|
|
|
|
|
|
|
|
``` bash
|
2023-05-23 17:59:26 -04:00
|
|
|
gcc -o foo -L. -lfoo foo.c # or g++ if using C++
|
2022-07-26 16:08:42 -04:00
|
|
|
```
|
|
|
|
|
|
2025-07-12 12:43:17 -04:00
|
|
|
Now running `./foo` will invoke `foo()` as defined in Codon, with an
|
2022-07-26 16:08:42 -04:00
|
|
|
argument of `10`.
|
|
|
|
|
|
2023-05-23 17:59:26 -04:00
|
|
|
Note that if the generated shared library is in a non-standard path, you
|
|
|
|
|
can either:
|
|
|
|
|
|
|
|
|
|
- Add the `rpath` to the `gcc` command: `-Wl,-rpath=/path/to/lib/dir`
|
|
|
|
|
- Add the library path to `LD_LIBRARY_PATH` (or `DYLD_LIBRARY_PATH` if
|
|
|
|
|
using macOS): `export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/path/to/lib/dir`.
|
|
|
|
|
|
2025-07-13 11:27:01 -04:00
|
|
|
Type conversions between Codon and C/C++ are detailed [here](cpp-from-codon.md#type-conversions).
|