ffi.txt 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. Foreign function interface
  2. ==========================
  3. Nim's `FFI`:idx: (foreign function interface) is extensive and only the
  4. parts that scale to other future backends (like the LLVM/JavaScript backends)
  5. are documented here.
  6. Importc pragma
  7. --------------
  8. The ``importc`` pragma provides a means to import a proc or a variable
  9. from C. The optional argument is a string containing the C identifier. If
  10. the argument is missing, the C name is the Nim identifier *exactly as
  11. spelled*:
  12. .. code-block::
  13. proc printf(formatstr: cstring) {.header: "<stdio.h>", importc: "printf", varargs.}
  14. Note that this pragma is somewhat of a misnomer: Other backends do provide
  15. the same feature under the same name. Also, if one is interfacing with C++
  16. the `ImportCpp pragma <manual.html#implementation-specific-pragmas-importcpp-pragma>`_ and
  17. interfacing with Objective-C the `ImportObjC pragma
  18. <manual.html#implementation-specific-pragmas-importobjc-pragma>`_ can be used.
  19. The string literal passed to ``importc`` can be a format string:
  20. .. code-block:: Nim
  21. proc p(s: cstring) {.importc: "prefix$1".}
  22. In the example the external name of ``p`` is set to ``prefixp``. Only ``$1``
  23. is available and a literal dollar sign must be written as ``$$``.
  24. Exportc pragma
  25. --------------
  26. The ``exportc`` pragma provides a means to export a type, a variable, or a
  27. procedure to C. Enums and constants can't be exported. The optional argument
  28. is a string containing the C identifier. If the argument is missing, the C
  29. name is the Nim identifier *exactly as spelled*:
  30. .. code-block:: Nim
  31. proc callme(formatstr: cstring) {.exportc: "callMe", varargs.}
  32. Note that this pragma is somewhat of a misnomer: Other backends do provide
  33. the same feature under the same name.
  34. The string literal passed to ``exportc`` can be a format string:
  35. .. code-block:: Nim
  36. proc p(s: string) {.exportc: "prefix$1".} =
  37. echo s
  38. In the example the external name of ``p`` is set to ``prefixp``. Only ``$1``
  39. is available and a literal dollar sign must be written as ``$$``.
  40. Extern pragma
  41. -------------
  42. Like ``exportc`` or ``importc``, the ``extern`` pragma affects name
  43. mangling. The string literal passed to ``extern`` can be a format string:
  44. .. code-block:: Nim
  45. proc p(s: string) {.extern: "prefix$1".} =
  46. echo s
  47. In the example the external name of ``p`` is set to ``prefixp``. Only ``$1``
  48. is available and a literal dollar sign must be written as ``$$``.
  49. Bycopy pragma
  50. -------------
  51. The ``bycopy`` pragma can be applied to an object or tuple type and
  52. instructs the compiler to pass the type by value to procs:
  53. .. code-block:: nim
  54. type
  55. Vector {.bycopy, pure.} = object
  56. x, y, z: float
  57. Byref pragma
  58. ------------
  59. The ``byref`` pragma can be applied to an object or tuple type and instructs
  60. the compiler to pass the type by reference (hidden pointer) to procs.
  61. Varargs pragma
  62. --------------
  63. The ``varargs`` pragma can be applied to procedures only (and procedure
  64. types). It tells Nim that the proc can take a variable number of parameters
  65. after the last specified parameter. Nim string values will be converted to C
  66. strings automatically:
  67. .. code-block:: Nim
  68. proc printf(formatstr: cstring) {.nodecl, varargs.}
  69. printf("hallo %s", "world") # "world" will be passed as C string
  70. Union pragma
  71. ------------
  72. The ``union`` pragma can be applied to any ``object`` type. It means all
  73. of the object's fields are overlaid in memory. This produces a ``union``
  74. instead of a ``struct`` in the generated C/C++ code. The object declaration
  75. then must not use inheritance or any GC'ed memory but this is currently not
  76. checked.
  77. **Future directions**: GC'ed memory should be allowed in unions and the GC
  78. should scan unions conservatively.
  79. Packed pragma
  80. -------------
  81. The ``packed`` pragma can be applied to any ``object`` type. It ensures
  82. that the fields of an object are packed back-to-back in memory. It is useful
  83. to store packets or messages from/to network or hardware drivers, and for
  84. interoperability with C. Combining packed pragma with inheritance is not
  85. defined, and it should not be used with GC'ed memory (ref's).
  86. **Future directions**: Using GC'ed memory in packed pragma will result in
  87. compile-time error. Usage with inheritance should be defined and documented.
  88. Unchecked pragma
  89. ----------------
  90. The ``unchecked`` pragma can be used to mark a named array as ``unchecked``
  91. meaning its bounds are not checked. This is often useful to
  92. implement customized flexibly sized arrays. Additionally an unchecked array is
  93. translated into a C array of undetermined size:
  94. .. code-block:: nim
  95. type
  96. ArrayPart{.unchecked.} = array[0, int]
  97. MySeq = object
  98. len, cap: int
  99. data: ArrayPart
  100. Produces roughly this C code:
  101. .. code-block:: C
  102. typedef struct {
  103. NI len;
  104. NI cap;
  105. NI data[];
  106. } MySeq;
  107. The base type of the unchecked array may not contain any GC'ed memory but this
  108. is currently not checked.
  109. **Future directions**: GC'ed memory should be allowed in unchecked arrays and
  110. there should be an explicit annotation of how the GC is to determine the
  111. runtime size of the array.
  112. Dynlib pragma for import
  113. ------------------------
  114. With the ``dynlib`` pragma a procedure or a variable can be imported from
  115. a dynamic library (``.dll`` files for Windows, ``lib*.so`` files for UNIX).
  116. The non-optional argument has to be the name of the dynamic library:
  117. .. code-block:: Nim
  118. proc gtk_image_new(): PGtkWidget
  119. {.cdecl, dynlib: "libgtk-x11-2.0.so", importc.}
  120. In general, importing a dynamic library does not require any special linker
  121. options or linking with import libraries. This also implies that no *devel*
  122. packages need to be installed.
  123. The ``dynlib`` import mechanism supports a versioning scheme:
  124. .. code-block:: nim
  125. proc Tcl_Eval(interp: pTcl_Interp, script: cstring): int {.cdecl,
  126. importc, dynlib: "libtcl(|8.5|8.4|8.3).so.(1|0)".}
  127. At runtime the dynamic library is searched for (in this order)::
  128. libtcl.so.1
  129. libtcl.so.0
  130. libtcl8.5.so.1
  131. libtcl8.5.so.0
  132. libtcl8.4.so.1
  133. libtcl8.4.so.0
  134. libtcl8.3.so.1
  135. libtcl8.3.so.0
  136. The ``dynlib`` pragma supports not only constant strings as argument but also
  137. string expressions in general:
  138. .. code-block:: nim
  139. import os
  140. proc getDllName: string =
  141. result = "mylib.dll"
  142. if existsFile(result): return
  143. result = "mylib2.dll"
  144. if existsFile(result): return
  145. quit("could not load dynamic library")
  146. proc myImport(s: cstring) {.cdecl, importc, dynlib: getDllName().}
  147. **Note**: Patterns like ``libtcl(|8.5|8.4).so`` are only supported in constant
  148. strings, because they are precompiled.
  149. **Note**: Passing variables to the ``dynlib`` pragma will fail at runtime
  150. because of order of initialization problems.
  151. **Note**: A ``dynlib`` import can be overriden with
  152. the ``--dynlibOverride:name`` command line option. The Compiler User Guide
  153. contains further information.
  154. Dynlib pragma for export
  155. ------------------------
  156. With the ``dynlib`` pragma a procedure can also be exported to
  157. a dynamic library. The pragma then has no argument and has to be used in
  158. conjunction with the ``exportc`` pragma:
  159. .. code-block:: Nim
  160. proc exportme(): int {.cdecl, exportc, dynlib.}
  161. This is only useful if the program is compiled as a dynamic library via the
  162. ``--app:lib`` command line option. This pragma only has an effect for the code
  163. generation on the Windows target, so when this pragma is forgotten and the dynamic
  164. library is only tested on Mac and/or Linux, there won't be an error. On Windows
  165. this pragma adds ``__declspec(dllexport)`` to the function declaration.