1
0
mirror of https://github.com/exaloop/codon.git synced 2025-06-03 15:03:52 +08:00
codon/docs/interop/cpp.md
A. R. Shajii d5ce1f8ff9
Update docs (#28)
* Update docs

* Update docs

* Update docs

* GitBook: [#4] Add hint

* Update primer

* Re-organize docs

* Fix table

* Fix link

* GitBook: [#5] No subject

* GitBook: [#6] No subject

* Cleanup and doc fix

* Add IR docs

* Add ir docs

* Fix spelling error

* More IR docs

* Update README.md

* Update README.md

* Fix warning

* Update intro

* Update README.md

* Update docs

* Fix table

* Don't build docs

* Update docs

* Add Jupyter docs

* FIx snippet

* Update README.md

* Fix images

* Fix code block

* Update docs, update cmake

* Break up tutorial

* Update pipeline.svg

* Update docs for new version

* Add differences with Python docs
2022-07-26 16:08:42 -04:00

56 lines
1.3 KiB
Markdown

Calling C/C++ from Codon is quite easy with `from C import`, but Codon
can also be called from C/C++ code. To make a Codon function externally
visible, simply annotate it with `@export`:
``` 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
*foo.codon*):
``` bash
codon build -o libfoo.so foo.codon
```
Now we can call `foo` from a C program:
``` c
#include <stdint.h>
#include <stdio.h>
int64_t foo(int64_t);
int main() {
printf("%llu\n", foo(10));
}
```
Compile:
``` bash
gcc -o foo -L. -lfoo foo.c
```
Now running `./foo` should invoke `foo()` as defined in Codon, with an
argument of `10`.
# Converting types
The following table shows the conversions between Codon and C/C++ types:
| Codon | C/C++ |
|-----------|--------------------------------------|
| `int` | `long` or `int64_t` |
| `float` | `double` |
| `bool` | `bool` |
| `byte` | `char` or `int8_t` |
| `str` | `{int64_t, char*}` (length and data) |
| `class` | Pointer to corresponding tuple |
| `@tuple` | Struct of fields |