Foreign language interop

Wrapping C

Using shared library

Example: secp256k1

Compiling directly the C files

Example: Apache Milagro Crypto

Wrapping C++

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

  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


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