2021-10-05 23:12:56 +08:00
Calling Codon from C/C++
========================
2021-09-28 02:02:44 +08:00
2021-10-05 23:12:56 +08:00
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 `` :
2021-09-28 02:02:44 +08:00
2021-10-05 23:12:56 +08:00
.. code-block :: python
2021-09-28 02:02:44 +08:00
@export
def foo(n: int):
for i in range(n):
print(i * i)
return n * n
2021-10-05 23:12:56 +08:00
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* ):
2021-09-28 02:02:44 +08:00
.. code-block :: bash
2021-10-05 23:12:56 +08:00
codon build -o foo.o foo.codon
gcc -shared -lcodonrt -lomp foo.o -o libfoo.so
2021-09-28 02:02:44 +08:00
2021-10-05 23:12:56 +08:00
(The last command might require an additional `` -L/path/to/codonrt/lib/ `` argument if `` libcodonrt `` is not installed on a standard path.)
2021-09-28 02:02:44 +08:00
Now we can call `` foo `` from a C program:
.. code-block :: C
#include <stdint.h>
#include <stdio.h>
int64_t foo(int64_t);
int main() {
printf("%llu\n", foo(10));
}
Compile:
.. code-block :: bash
gcc -o foo -L. -lfoo foo.c
2021-10-05 23:12:56 +08:00
Now running `` ./foo `` should invoke `` foo() `` as defined in Codon, with an argument of `` 10 `` .
2021-09-28 02:02:44 +08:00
Converting types
----------------
2021-10-05 23:12:56 +08:00
The following table shows the conversions between Codon and C/C++ types:
2021-09-28 02:02:44 +08:00
============ ============
2021-10-06 02:44:32 +08:00
**Codon** **C/C++**
2021-09-28 02:02:44 +08:00
------------ ------------
2021-10-06 02:44:32 +08:00
`` int `` `` long `` or `` int64_t ``
2021-09-28 02:02:44 +08:00
`` float `` `` double ``
`` bool `` `` bool ``
2021-10-06 02:44:32 +08:00
`` byte `` `` char `` or `` int8_t ``
`` str `` `` {int64_t, char*} `` (length and data)
2021-09-28 02:02:44 +08:00
`` class `` Pointer to corresponding tuple
`` @tuple `` Struct of fields
============ ============