Foreign language interop

!!! warning This auditors' handbook is frozen and obsolete; the Nim language manual alongside other Nim documentation, Status Nim style guide, Chronos guides, and Nim by Example supercede it.

Wrapping C

Using shared library

Example: secp256k1

https://github.com/status-im/nim-secp256k1/blob/master/secp256k1_abi.nim

Compiling directly the C files

Example: MIRACL Core

https://github.com/status-im/nim-blscurve/blob/master/blscurve/miracl/miracl.nim

Wrapping C++

Beyond the syntax for wrapping C, Nim offers a flexible syntax for wrapping C++, for example for vectors:

type
  CppVector* {.importcpp"std::vector", header: "<vector>", byref.} [T] = object

proc newCppVector*[T](): CppVector[T] {.importcpp: "std::vector<'*0>()", header: "<vector>", constructor.}
proc newCppVector*[T](size: int): CppVector[T] {.importcpp: "std::vector<'*0>(#)", header: "<vector>", constructor.}
proc len*(v: CppVector): int {.importcpp: "#.size()", header: "<vector>".}
proc add*[T](v: var CppVector[T], elem: T){.importcpp: "#.push_back(#)", header: "<vector>".}
proc `[]`*[T](v: CppVector[T], idx: int): T{.importcpp: "#[#]", header: "<vector>".}
proc `[]`*[T](v: var CppVector[T], idx: int): var T{.importcpp: "#[#]", header: "<vector>".}
proc `[]=`*[T](v: var CppVector[T], idx: int, value: T) {.importcpp: "#[#]=#", header: "<vector>".}

Example: ttmath

https://github.com/status-im/nim-ttmath/blob/master/src/ttmath.nim

Exporting

See "Fuzzing" chapter for exporting a C API for fuzzing

References