Chuyển đến nội dung

Bài 30 · FFI and Tooling

Calling C from Nim with importc

Learn Nim's foreign function interface: importc and header pragmas, cstring and C types, structs and callbacks, linking libraries, and exporting Nim procs to C.

Nim compiles to C, so calling C libraries is easy and costs nothing at run time. There is no wrapper layer: an imported function is just a call in the generated C code. This is how Nim gets access to thousands of existing libraries (SQLite, SDL, zlib, OpenSSL) and how you can mix Nim into an existing C project.

The Nim compiler is not available on this site, so the Nim snippets are read-only. The runnable C stand-ins are the C side of each example, so you can see the code that Nim would call.

importc

The {.importc.} pragma declares a proc that is implemented elsewhere. Pair it with header to tell the generated C file which header to include, or with dynlib to load a shared library at run time.

NIM
proc c_abs(x: cint): cint {.importc: "abs", header: "<stdlib.h>".}
proc c_strlen(s: cstring): csize_t {.importc: "strlen", header: "<string.h>".}

echo c_abs(-5)            # 5
echo c_strlen("nim")      # 3

The name inside importc is the C name; the Nim name can be anything. Types must match C exactly, so Nim provides aliases: cint, cuint, clong, cdouble, csize_t, cstring (a char*), pointer, and ptr T.

C C stand-in: the C functions Nim would call

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Strings across the boundary

A Nim string is not a C string. A cstring is a raw char* to a zero-terminated buffer. Converting a Nim string with cstring(s) gives a pointer that is valid only while the Nim string lives and is not modified, and $c converts back by copying.

NIM
let name = "world"
discard c_puts(cstring("hello " & name))   # the temporary is alive during the call
let back: string = $someCString

Never keep a cstring from a temporary string after the call returns.

Structs and callbacks

Declare a C struct with {.importc.} and {.bycopy.} (pass by value like C) or mirror its layout by field order. A callback needs {.cdecl.} so that Nim uses the C calling convention.

NIM
type Point {.bycopy.} = object
  x, y: cdouble

proc cmpInt(a, b: pointer): cint {.cdecl.} =
  let x = cast[ptr cint](a)[]
  let y = cast[ptr cint](b)[]
  if x < y: -1 elif x > y: 1 else: 0

proc qsort(base: pointer, n, size: csize_t,
           cmp: proc (a, b: pointer): cint {.cdecl.}) {.importc, header: "<stdlib.h>".}

var data = [5.cint, 1, 4]
qsort(addr data[0], csize_t(data.len), csize_t(sizeof(cint)), cmpInt)

The stand-in is the same call in C:

C C stand-in: qsort with a callback

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Linking libraries

Tell the compiler what to link with pragmas or command-line flags:

NIM
{.passL: "-lm".}                       # link libm
proc c_sqrt(x: cdouble): cdouble {.importc: "sqrt", header: "<math.h>".}

# or load at run time
proc sqliteVersion(): cstring {.importc: "sqlite3_libversion", dynlib: "libsqlite3.so".}

Use {.compile: "mylib.c".} to compile a C file alongside your program, with no build system at all. For big headers, the c2nim tool translates C declarations into Nim, and wrapper packages already exist for common libraries (see Nimble and Packages).

Exporting Nim to C

The reverse direction: {.exportc.} gives a proc a C name, and --app:lib builds a shared library.

NIM
proc add(a, b: cint): cint {.exportc: "nim_add", cdecl, dynlib.} = a + b
Text
nim c --app:lib --noMain --mm:arc mylib.nim

The caller sees an ordinary C function nim_add. With --noMain the host program must call NimMain() once before using Nim code that needs initialization. Prefer --mm:arc or orc for libraries (see Memory Management).

C C stand-in: the C caller of nim_add

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Common mistakes

  • Using Nim int where C expects int: use cint. Nim int is pointer sized (64-bit on a 64-bit system) and the two differ.
  • Forgetting {.cdecl.} on callbacks.
  • Passing a Nim seq where a pointer is needed: use addr s[0] after checking it is not empty, or s.toOpenArray.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does {.importc.} do?

    It makes the generated C code call an existing C function by name.
  2. 2. Which Nim type corresponds to C int?

    cint is a C int; Nim int is pointer sized.
  3. 3. Why is {.cdecl.} needed on callbacks?

    C code calls the callback, so it must follow the C convention.
  4. 4. How do you build a shared library from Nim?

    --app:lib produces a shared library.

Summary

  • importc plus header or dynlib calls C directly with no overhead.
  • Use cint, cstring and friends to match C types; mind string lifetimes.
  • {.cdecl.} is required for callbacks; {.compile.} and {.passL.} handle building.
  • exportc and --app:lib expose Nim to C.

Next: Nimble and Packages

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.