C interoperability
Author: | Admin |
Title: | Nim playground, C interoperability |
Language: | en-US |
Number of words: | 112 |
Category: | Nim |
Created: | 10:39 on Thursday, 16. June 2022 |
Modified: | 10:39 on Thursday, 16. June 2022 |
Keywords: | nim, code, interoperability |
Excerpt: | Technically, Nim is a transpiled language. It uses C as intermediate language and „under the hood” it has a lot of things common with C. Interfacing with existing C code is therefore relatively easy and makes Nim an excellent choice for system programming. |
Tags: | nim |
Page layout: | no_sidebar |
This is particularly easy in Nim, because Nim first transpiles to C and is then compiled by the C compiler of choice. It’s therefore quite easy to import from C libraries.
Code: (click to select all)
1
2
3
4
proc printf*(format: cstring): cint {.importc, header: "<stdio.h>", varargs.}
proc fprintf*(stream: File, format: cstring): cint {.importc, header: "<stdio.h>".}
proc sprintf*(str: cstring, format: cstring): cint {.header: "<stdio.h>", importc: "sprintf", varargs.}
proc snprintf*(str: cstring, len: int, format: cstring): cint {.header: "<stdio.h>", importc: "snprintf", varargs.}
Here, we import a couple of known C functions from the C standard library.