backends.html 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <!-- This file is generated by Nim. -->
  4. <html xmlns="https://www.w3.org/1999/xhtml" xml:lang="en" lang="en" data-theme="auto">
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  7. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  8. <title>Nim Backend Integration</title>
  9. <!-- Google fonts -->
  10. <link href='https://fonts.googleapis.com/css?family=Lato:400,600,900' rel='stylesheet' type='text/css'/>
  11. <link href='https://fonts.googleapis.com/css?family=Source+Code+Pro:400,500,600' rel='stylesheet' type='text/css'/>
  12. <!-- Favicon -->
  13. <link rel="shortcut icon" href="data:image/x-icon;base64,AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAUAAAAF////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAIAAABbAAAAlQAAAKIAAACbAAAAmwAAAKIAAACVAAAAWwAAAAL///8A////AP///wD///8A////AAAAABQAAADAAAAAYwAAAA3///8A////AP///wD///8AAAAADQAAAGMAAADAAAAAFP///wD///8A////AP///wAAAACdAAAAOv///wD///8A////AP///wD///8A////AP///wD///8AAAAAOgAAAJ3///8A////AP///wAAAAAnAAAAcP///wAAAAAoAAAASv///wD///8A////AP///wAAAABKAAAAKP///wAAAABwAAAAJ////wD///8AAAAAgQAAABwAAACIAAAAkAAAAJMAAACtAAAAFQAAABUAAACtAAAAkwAAAJAAAACIAAAAHAAAAIH///8A////AAAAAKQAAACrAAAAaP///wD///8AAAAARQAAANIAAADSAAAARf///wD///8AAAAAaAAAAKsAAACk////AAAAADMAAACcAAAAnQAAABj///8A////AP///wAAAAAYAAAAGP///wD///8A////AAAAABgAAACdAAAAnAAAADMAAAB1AAAAwwAAAP8AAADpAAAAsQAAAE4AAAAb////AP///wAAAAAbAAAATgAAALEAAADpAAAA/wAAAMMAAAB1AAAAtwAAAOkAAAD/AAAA/wAAAP8AAADvAAAA3gAAAN4AAADeAAAA3gAAAO8AAAD/AAAA/wAAAP8AAADpAAAAtwAAAGUAAAA/AAAA3wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAADfAAAAPwAAAGX///8A////AAAAAEgAAADtAAAAvwAAAL0AAADGAAAA7wAAAO8AAADGAAAAvQAAAL8AAADtAAAASP///wD///8A////AP///wD///8AAAAAO////wD///8A////AAAAAIcAAACH////AP///wD///8AAAAAO////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A//8AAP//AAD4HwAA7/cAAN/7AAD//wAAoYUAAJ55AACf+QAAh+EAAAAAAADAAwAA4AcAAP5/AAD//wAA//8AAA=="/>
  14. <link rel="icon" type="image/png" sizes="32x32" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAA3XAAAN1wFCKJt4AAAAB3RJTUUH4QQQEwksSS9ZWwAAAk1JREFUWMPtll2ITVEUx39nn/O7Y5qR8f05wtCUUr6ZIS++8pEnkZInPImneaCQ5METNdOkeFBKUhMPRIkHKfEuUZSUlGlKPN2TrgfncpvmnntnmlEyq1Z7t89/rf9a6+y99oZxGZf/XeIq61EdtgKXgdXA0xrYAvBjOIF1AI9zvjcC74BSpndrJPkBWDScTF8Aa4E3wDlgHbASaANmVqlcCnwHvgDvgVfAJ+AikAAvgfVZwLnSVZHZaOuKoQi3ZOMi4NkYkpe1p4J7A8BpYAD49hfIy/oqG0+hLomiKP2L5L+1ubn5115S+3OAn4EnwBlgMzCjyt6ZAnQCJ4A7wOs88iRJHvw50HoujuPBoCKwHWiosy8MdfZnAdcHk8dxXFJ3VQbQlCTJvRBCGdRbD4M6uc5glpY3eAihpN5S5w12diSEcCCEcKUO4ljdr15T76ur1FDDLIQQ3qv71EdDOe3Kxj3leRXyk+pxdWnFWod6Wt2bY3de3aSuUHcPBVimHs7mK9WrmeOF6lR1o9qnzskh2ar2qm1qizpfXaPeVGdlmGN5pb09qMxz1Xb1kLqgzn1RyH7JUXW52lr5e/Kqi9qpto7V1atuUzfnARrV7jEib1T76gG2qxdGmXyiekkt1GswPTtek0aBfJp6YySGBfWg2tPQ0FAYgf1stUfdmdcjarbYJEniKIq6gY/Aw+zWHAC+p2labGpqiorFYgGYCEzN7oQdQClN07O1/EfDyGgC0ALMBdYAi4FyK+4H3gLPsxfR1zRNi+NP7nH5J+QntnXe5B5mpfQAAAAASUVORK5CYII=">
  15. <!-- CSS -->
  16. <link rel="stylesheet" type="text/css" href="nimdoc.out.css?v=2.3.1">
  17. <!-- JS -->
  18. <script type="text/javascript" src="dochack.js?v=2.3.1"></script>
  19. </head>
  20. <body>
  21. <div class="document" id="documentId">
  22. <div class="container">
  23. <h1 class="title">Nim Backend Integration</h1>
  24. <div class="row">
  25. <div class="three columns">
  26. <div class="theme-select-wrapper">
  27. <label for="theme-select">Theme:&nbsp;</label>
  28. <select id="theme-select" onchange="setTheme(this.value)">
  29. <option value="auto">🌗 Match OS</option>
  30. <option value="dark">🌑 Dark</option>
  31. <option value="light">🌕 Light</option>
  32. </select>
  33. </div>
  34. <div id="global-links">
  35. <ul class="simple-boot">
  36. <li><a href="manual.html">Manual</a></li>
  37. <li><a href="lib.html">Standard library</a></li>
  38. <li> <a id="indexLink" href="theindex.html">Index</a></li>
  39. <li><a href="compiler/theindex.html">Compiler docs</a></li>
  40. <li><a href="https://nim-lang.github.io/fusion/theindex.html">Fusion docs</a></li>
  41. <li><a href="https://nim-lang.github.io/Nim/">devel</a>, <a href="https://nim-lang.org/documentation.html">stable</a></li>
  42. </ul>
  43. </div>
  44. <div id="searchInputDiv">
  45. Search: <input type="search" id="searchInput"
  46. oninput="search()" />
  47. </div>
  48. <div class="search-groupby">
  49. Group by:
  50. <select onchange="groupBy(this.value)">
  51. <option value="section">Section</option>
  52. <option value="type">Type</option>
  53. </select>
  54. </div>
  55. <ul class="simple simple-toc" id="toc-list">
  56. <li><a class="reference" id="introduction_toc" href="#introduction">Introduction</a></li>
  57. <li><a class="reference" id="backends_toc" href="#backends">Backends</a></li>
  58. <ul class="simple"><li><a class="reference" id="backends-the-c-like-targets_toc" href="#backends-the-c-like-targets">The C like targets</a></li>
  59. <li><a class="reference" id="backends-the-javascript-target_toc" href="#backends-the-javascript-target">The JavaScript target</a></li>
  60. </ul><li><a class="reference" id="interfacing_toc" href="#interfacing">Interfacing</a></li>
  61. <ul class="simple"><li><a class="reference" id="interfacing-nim-code-calling-the-backend_toc" href="#interfacing-nim-code-calling-the-backend">Nim code calling the backend</a></li>
  62. <ul class="simple"><li><a class="reference" id="nim-code-calling-the-backend-c-invocation-example_toc" href="#nim-code-calling-the-backend-c-invocation-example">C invocation example</a></li>
  63. <li><a class="reference" id="nim-code-calling-the-backend-javascript-invocation-example_toc" href="#nim-code-calling-the-backend-javascript-invocation-example">JavaScript invocation example</a></li>
  64. </ul><li><a class="reference" id="interfacing-backend-code-calling-nim_toc" href="#interfacing-backend-code-calling-nim">Backend code calling Nim</a></li>
  65. <ul class="simple"><li><a class="reference" id="backend-code-calling-nim-nim-invocation-example-from-c_toc" href="#backend-code-calling-nim-nim-invocation-example-from-c">Nim invocation example from C</a></li>
  66. <li><a class="reference" id="backend-code-calling-nim-nim-invocation-example-from-javascript_toc" href="#backend-code-calling-nim-nim-invocation-example-from-javascript">Nim invocation example from JavaScript</a></li>
  67. </ul><li><a class="reference" id="interfacing-nimcache-naming-logic_toc" href="#interfacing-nimcache-naming-logic">Nimcache naming logic</a></li>
  68. </ul><li><a class="reference" id="memory-management_toc" href="#memory-management">Memory management</a></li>
  69. <ul class="simple"><li><a class="reference" id="memory-management-strings-and-c-strings_toc" href="#memory-management-strings-and-c-strings">Strings and C strings</a></li>
  70. <li><a class="reference" id="memory-management-custom-data-types_toc" href="#memory-management-custom-data-types">Custom data types</a></li>
  71. </ul>
  72. </ul>
  73. </div>
  74. <div class="nine columns" id="content">
  75. <a href="https://github.com/nim-lang/Nim/tree/devel/doc/backends.md#L1" class="link-seesrc" target="_blank">Source</a>&nbsp;&nbsp;
  76. <a href="https://github.com/nim-lang/Nim/edit/devel/doc/backends.md#L1" class="link-seesrc" target="_blank" >Edit</a>&nbsp;&nbsp;
  77. <div id="tocRoot"></div>
  78. <p class="module-desc"><table class="docinfo" frame="void" rules="none"><col class="docinfo-name" /><col class="docinfo-content" /><tbody valign="top"><tr><th class="docinfo-name">Author:</th><td>Puppet Master</td></tr>
  79. <tr><th class="docinfo-name">Version:</th><td>2.3.1</td></tr>
  80. </tbody></table><blockquote class="markdown-quote"><p>&quot;Heresy grows from idleness.&quot; -- Unknown.</p></blockquote>
  81. <h1><a class="toc-backref" id="introduction" href="#introduction">Introduction</a></h1><p>The <a class="reference external" href="nimc.html">Nim Compiler User Guide</a> documents the typical compiler invocation, using the <tt class="docutils literal"><span class="pre option">compile</span></tt> or <tt class="docutils literal"><span class="pre option">c</span></tt> command to transform a <tt class="docutils literal"><span class="pre">.nim</span></tt> file into one or more <tt class="docutils literal"><span class="pre">.c</span></tt> files which are then compiled with the platform's C compiler into a static binary. However, there are other commands to compile to C++, Objective-C, or JavaScript. This document tries to concentrate in a single place all the backend and interfacing options.</p>
  82. <p>The Nim compiler supports mainly two backend families: the C, C++ and Objective-C targets and the JavaScript target. <a class="reference external" href=" #backends-the-c-like-targets">The C like targets</a> creates source files that can be compiled into a library or a final executable. <a class="reference external" href=" #backends-the-javascript-target">The JavaScript target</a> can generate a <tt class="docutils literal"><span class="pre">.js</span></tt> file which you reference from an HTML file or create a <a class="reference external" href=" https://nodejs.org">standalone Node.js program</a>.</p>
  83. <p>On top of generating libraries or standalone applications, Nim offers bidirectional interfacing with the backend targets through generic and specific pragmas.</p>
  84. <h1><a class="toc-backref" id="backends" href="#backends">Backends</a></h1>
  85. <h2><a class="toc-backref" id="backends-the-c-like-targets" href="#backends-the-c-like-targets">The C like targets</a></h2><p>The commands to compile to either C, C++ or Objective-C are:</p>
  86. <div class="option-list"><div class="option-list-item odd"><div class="option-list-label"><tt><span class="option">compileToC, cc</span></tt></div><div class="option-list-description">compile project with C code generator</div></div>
  87. <div class="option-list-item"><div class="option-list-label"><tt><span class="option">compileToCpp, cpp</span></tt></div><div class="option-list-description">compile project to C++ code</div></div>
  88. <div class="option-list-item odd"><div class="option-list-label"><tt><span class="option">compileToOC, objc</span></tt></div><div class="option-list-description">compile project to Objective C code</div></div>
  89. </div><p>The most significant difference between these commands is that if you look into the <tt class="docutils literal"><span class="pre">nimcache</span></tt> directory you will find <tt class="docutils literal"><span class="pre">.c</span></tt>, <tt class="docutils literal"><span class="pre">.cpp</span></tt> or <tt class="docutils literal"><span class="pre">.m</span></tt> files, other than that all of them will produce a native binary for your project. This allows you to take the generated code and place it directly into a project using any of these languages. Here are some typical command- line invocations:</p>
  90. <p><pre class="listing"><span class="program">nim</span> <span class="option">c</span> <span class="Identifier">hallo.nim</span>
  91. <span class="program">nim</span> <span class="option">cpp</span> <span class="Identifier">hallo.nim</span>
  92. <span class="program">nim</span> <span class="option">objc</span> <span class="Identifier">hallo.nim</span></pre></p>
  93. <p>The compiler commands select the target backend, but if needed you can <a class="reference external" href=" nimc.html#crossminuscompilation">specify additional switches for cross-compilation</a> to select the target CPU, operative system or compiler/linker commands.</p>
  94. <h2><a class="toc-backref" id="backends-the-javascript-target" href="#backends-the-javascript-target">The JavaScript target</a></h2><p>Nim can also generate <span id="javascript_1">JavaScript</span> code through the <tt class="docutils literal"><span class="pre option">js</span></tt> command.</p>
  95. <p>Nim targets JavaScript 1.5 which is supported by any widely used browser. Since JavaScript does not have a portable means to include another module, Nim just generates a long <tt class="docutils literal"><span class="pre">.js</span></tt> file.</p>
  96. <p>Features or modules that the JavaScript platform does not support are not available. This includes:</p>
  97. <ul class="simple"><li>manual memory management (<tt class="docutils literal"><span class="pre"><span class="Identifier">alloc</span></span></tt>, etc.)</li>
  98. <li>casting and other unsafe operations (<tt class="docutils literal"><span class="pre"><span class="Keyword">cast</span></span></tt> operator, <tt class="docutils literal"><span class="pre"><span class="Identifier">zeroMem</span></span></tt>, etc.)</li>
  99. <li>file management</li>
  100. <li>OS-specific operations</li>
  101. <li>threading, coroutines</li>
  102. <li>some modules of the standard library</li>
  103. </ul>
  104. <p>To compensate, the standard library has modules <a class="reference external" href=" lib.html#pure-libraries-modules-for-the-javascript-backend">catered to the JS backend</a> and more support will come in the future (for instance, Node.js bindings to get OS info).</p>
  105. <p>To compile a Nim module into a <tt class="docutils literal"><span class="pre">.js</span></tt> file use the <tt class="docutils literal"><span class="pre option">js</span></tt> command; the default is a <tt class="docutils literal"><span class="pre">.js</span></tt> file that is supposed to be referenced in an <tt class="docutils literal"><span class="pre">.html</span></tt> file. However, you can also run the code with <span id="nodejs_1">nodejs</span> (<a class="reference external" href="https://nodejs.org">https://nodejs.org</a>):</p>
  106. <p><pre class="listing"><span class="program">nim</span> <span class="option">js</span> <span class="option">-r</span> <span class="Identifier">examples/hallo.nim</span></pre></p>
  107. <p>If you experience errors saying that <tt class="docutils literal"><span class="pre"><span class="Identifier">globalThis</span></span></tt> is not defined, be sure to run a recent version of Node.js (at least 12.0).</p>
  108. <h1><a class="toc-backref" id="interfacing" href="#interfacing">Interfacing</a></h1><p>Nim offers bidirectional interfacing with the target backend. This means that you can call backend code from Nim and Nim code can be called by the backend code. Usually the direction of which calls which depends on your software architecture (is Nim your main program or is Nim providing a component?).</p>
  109. <h2><a class="toc-backref" id="interfacing-nim-code-calling-the-backend" href="#interfacing-nim-code-calling-the-backend">Nim code calling the backend</a></h2><p>Nim code can interface with the backend through the <a class="reference external" href="manual.html#foreign-function-interface">Foreign function interface</a> mainly through the <a class="reference external" href="manual.html#foreign-function-interface-importc-pragma">importc pragma</a>. The <tt class="docutils literal"><span class="pre"><span class="Identifier">importc</span></span></tt> pragma is the <em>generic</em> way of making backend symbols available in Nim and is available in all the target backends (JavaScript too). The C++ or Objective-C backends have their respective <a class="reference external" href=" manual.html#implementation-specific-pragmas-importcpp-pragma">ImportCpp</a> and <a class="reference external" href="manual.html#implementation-specific-pragmas-importobjc-pragma">ImportObjC</a> pragmas to call methods from classes.</p>
  110. <p>Whenever you use any of these pragmas you need to integrate native code into your final binary. In the case of JavaScript this is no problem at all, the same HTML file which hosts the generated JavaScript will likely provide other JavaScript functions which you are importing with <tt class="docutils literal"><span class="pre"><span class="Identifier">importc</span></span></tt>.</p>
  111. <p>However, for the C like targets you need to link external code either statically or dynamically. The preferred way of integrating native code is to use dynamic linking because it allows you to compile Nim programs without the need for having the related development libraries installed. This is done through the <a class="reference external" href=" manual.html#foreign-function-interface-dynlib-pragma-for-import">dynlib pragma for import</a>, though more specific control can be gained using the <a class="reference external" href="dynlib.html">dynlib module</a>.</p>
  112. <p>The <a class="reference external" href="nimc.html#dynliboverride">dynlibOverride</a> command line switch allows to avoid dynamic linking if you need to statically link something instead. Nim wrappers designed to statically link source files can use the <a class="reference external" href="manual.html#implementation-specific-pragmas-compile-pragma">compile pragma</a> if there are few sources or providing them along the Nim code is easier than using a system library. Libraries installed on the host system can be linked in with the <a class="reference external" href="manual.html#implementation-specific-pragmas-passl-pragma">PassL pragma</a>.</p>
  113. <p>To wrap native code, take a look at the <a class="reference external" href=" https://github.com/nim-lang/c2nim/blob/master/doc/c2nim.rst">c2nim tool</a> which helps with the process of scanning and transforming header files into a Nim interface.</p>
  114. <h3><a class="toc-backref" id="nim-code-calling-the-backend-c-invocation-example" href="#nim-code-calling-the-backend-c-invocation-example">C invocation example</a></h3><p>Create a <tt class="docutils literal"><span class="pre">logic.c</span></tt> file with the following content:</p>
  115. <p><pre class="listing"><span class="Keyword">int</span> <span class="Identifier">addTwoIntegers</span><span class="Punctuation">(</span><span class="Keyword">int</span> <span class="Identifier">a</span><span class="Punctuation">,</span> <span class="Keyword">int</span> <span class="Identifier">b</span><span class="Punctuation">)</span>
  116. <span class="Punctuation">{</span>
  117. <span class="Keyword">return</span> <span class="Identifier">a</span> <span class="Operator">+</span> <span class="Identifier">b</span><span class="Punctuation">;</span>
  118. <span class="Punctuation">}</span></pre></p>
  119. <p>Create a <tt class="docutils literal"><span class="pre">calculator.nim</span></tt> file with the following content:</p>
  120. <p><pre class="listing"><span class="Punctuation">{</span><span class="Operator">.</span><span class="Identifier">compile</span><span class="Punctuation">:</span> <span class="StringLit">&quot;logic.c&quot;</span><span class="Operator">.</span><span class="Punctuation">}</span>
  121. <span class="Keyword">proc</span> <span class="Identifier">addTwoIntegers</span><span class="Punctuation">(</span><span class="Identifier">a</span><span class="Punctuation">,</span> <span class="Identifier">b</span><span class="Punctuation">:</span> <span class="Identifier">cint</span><span class="Punctuation">)</span><span class="Punctuation">:</span> <span class="Identifier">cint</span> <span class="Punctuation">{</span><span class="Operator">.</span><span class="Identifier">importc</span><span class="Operator">.</span><span class="Punctuation">}</span>
  122. <span class="Keyword">when</span> <span class="Identifier">isMainModule</span><span class="Punctuation">:</span>
  123. <span class="Identifier">echo</span> <span class="Identifier">addTwoIntegers</span><span class="Punctuation">(</span><span class="DecNumber">3</span><span class="Punctuation">,</span> <span class="DecNumber">7</span><span class="Punctuation">)</span></pre></p>
  124. <p>With these two files in place, you can run <tt class="docutils literal"><span class="pre"><span class="program">nim</span> <span class="option">c</span> <span class="option">-r</span> <span class="Identifier">calculator.nim</span></span></tt> and the Nim compiler will compile the <tt class="docutils literal"><span class="pre">logic.c</span></tt> file in addition to <tt class="docutils literal"><span class="pre">calculator.nim</span></tt> and link both into an executable, which outputs <tt class="docutils literal"><span class="pre"><span class="DecNumber">10</span></span></tt> when run. Another way to link the C file statically and get the same effect would be to remove the line with the <tt class="docutils literal"><span class="pre"><span class="Identifier">compile</span></span></tt> pragma and run the following typical Unix commands:</p>
  125. <p><pre class="listing"><span class="program">gcc</span> <span class="option">-c</span> <span class="Identifier">logic.c</span>
  126. <span class="program">ar</span> <span class="option">rvs</span> <span class="Identifier">mylib.a</span> <span class="Identifier">logic.o</span>
  127. <span class="program">nim</span> <span class="option">c</span> <span class="Identifier">--passL:mylib.a</span> <span class="option">-r</span> <span class="Identifier">calculator.nim</span></pre></p>
  128. <p>Just like in this example we pass the path to the <tt class="docutils literal"><span class="pre">mylib.a</span></tt> library (and we could as well pass <tt class="docutils literal"><span class="pre">logic.o</span></tt>) we could be passing switches to link any other static C library.</p>
  129. <h3><a class="toc-backref" id="nim-code-calling-the-backend-javascript-invocation-example" href="#nim-code-calling-the-backend-javascript-invocation-example">JavaScript invocation example</a></h3><p>Create a <tt class="docutils literal"><span class="pre">host.html</span></tt> file with the following content:</p>
  130. <p><pre class="listing">&lt;html&gt;&lt;body&gt;
  131. &lt;script type=&quot;text/javascript&quot;&gt;
  132. function addTwoIntegers(a, b)
  133. {
  134. return a + b;
  135. }
  136. &lt;/script&gt;
  137. &lt;script type=&quot;text/javascript&quot; src=&quot;calculator.js&quot;&gt;&lt;/script&gt;
  138. &lt;/body&gt;&lt;/html&gt;</pre></p>
  139. <p>Create a <tt class="docutils literal"><span class="pre">calculator.nim</span></tt> file with the following content (or reuse the one from the previous section):</p>
  140. <p><pre class="listing"><span class="Keyword">proc</span> <span class="Identifier">addTwoIntegers</span><span class="Punctuation">(</span><span class="Identifier">a</span><span class="Punctuation">,</span> <span class="Identifier">b</span><span class="Punctuation">:</span> <span class="Identifier">int</span><span class="Punctuation">)</span><span class="Punctuation">:</span> <span class="Identifier">int</span> <span class="Punctuation">{</span><span class="Operator">.</span><span class="Identifier">importc</span><span class="Operator">.</span><span class="Punctuation">}</span>
  141. <span class="Keyword">when</span> <span class="Identifier">isMainModule</span><span class="Punctuation">:</span>
  142. <span class="Identifier">echo</span> <span class="Identifier">addTwoIntegers</span><span class="Punctuation">(</span><span class="DecNumber">3</span><span class="Punctuation">,</span> <span class="DecNumber">7</span><span class="Punctuation">)</span></pre></p>
  143. <p>Compile the Nim code to JavaScript with <tt class="docutils literal"><span class="pre"><span class="program">nim</span> <span class="option">js</span> <span class="Identifier">-o:calculator.js</span> <span class="Identifier">calculator.nim</span></span></tt> and open <tt class="docutils literal"><span class="pre">host.html</span></tt> in a browser. If the browser supports javascript, you should see the value <tt class="docutils literal"><span class="pre"><span class="DecNumber">10</span></span></tt> in the browser's console. Use the <a class="reference external" href="dom.html">dom module</a> for specific DOM querying and modification procs or take a look at <a class="reference external" href="https://github.com/pragmagic/karax">karax</a> for how to develop browser-based applications.</p>
  144. <h2><a class="toc-backref" id="interfacing-backend-code-calling-nim" href="#interfacing-backend-code-calling-nim">Backend code calling Nim</a></h2><p>Backend code can interface with Nim code exposed through the <a class="reference external" href="manual.html#foreign-function-interface-exportc-pragma">exportc pragma</a>. The <tt class="docutils literal"><span class="pre"><span class="Identifier">exportc</span></span></tt> pragma is the <em>generic</em> way of making Nim symbols available to the backends. By default, the Nim compiler will mangle all the Nim symbols to avoid any name collision, so the most significant thing the <tt class="docutils literal"><span class="pre"><span class="Identifier">exportc</span></span></tt> pragma does is maintain the Nim symbol name, or if specified, use an alternative symbol for the backend in case the symbol rules don't match.</p>
  145. <p>The JavaScript target doesn't have any further interfacing considerations since it also has garbage collection, but the C targets require you to initialize Nim's internals, which is done calling a <tt class="docutils literal"><span class="pre"><span class="Identifier">NimMain</span></span></tt> function. Also, C code requires you to specify a forward declaration for functions or the compiler will assume certain types for the return value and parameters which will likely make your program crash at runtime.</p>
  146. <p>The name <tt class="docutils literal"><span class="pre"><span class="Identifier">NimMain</span></span></tt> can be influenced via the <tt class="docutils literal"><span class="pre"><span class="Operator">--</span><span class="Identifier">nimMainPrefix</span><span class="Punctuation">:</span><span class="Identifier">prefix</span></span></tt> switch. Use <tt class="docutils literal"><span class="pre"><span class="Operator">--</span><span class="Identifier">nimMainPrefix</span><span class="Punctuation">:</span><span class="Identifier">MyLib</span></span></tt> and the function to call is named <tt class="docutils literal"><span class="pre"><span class="Identifier">MyLibNimMain</span></span></tt>.</p>
  147. <p>When compiling to static or dynamic libraries, they don't call destructors of global variables as normal Nim programs would do. A C API <tt class="docutils literal"><span class="pre"><span class="Identifier">NimDestroyGlobals</span></span></tt> is provided to call these global destructors. It is influenced by the <tt class="docutils literal"><span class="pre"><span class="Operator">--</span><span class="Identifier">nimMainPrefix</span><span class="Punctuation">:</span><span class="Identifier">prefix</span></span></tt> switch, too.</p>
  148. <h3><a class="toc-backref" id="backend-code-calling-nim-nim-invocation-example-from-c" href="#backend-code-calling-nim-nim-invocation-example-from-c">Nim invocation example from C</a></h3><p>Create a <tt class="docutils literal"><span class="pre">fib.nim</span></tt> file with the following content:</p>
  149. <p><pre class="listing"><span class="Keyword">proc</span> <span class="Identifier">fib</span><span class="Punctuation">(</span><span class="Identifier">a</span><span class="Punctuation">:</span> <span class="Identifier">cint</span><span class="Punctuation">)</span><span class="Punctuation">:</span> <span class="Identifier">cint</span> <span class="Punctuation">{</span><span class="Operator">.</span><span class="Identifier">exportc</span><span class="Operator">.</span><span class="Punctuation">}</span> <span class="Operator">=</span>
  150. <span class="Keyword">if</span> <span class="Identifier">a</span> <span class="Operator">&lt;=</span> <span class="DecNumber">2</span><span class="Punctuation">:</span>
  151. <span class="Identifier">result</span> <span class="Operator">=</span> <span class="DecNumber">1</span>
  152. <span class="Keyword">else</span><span class="Punctuation">:</span>
  153. <span class="Identifier">result</span> <span class="Operator">=</span> <span class="Identifier">fib</span><span class="Punctuation">(</span><span class="Identifier">a</span> <span class="Operator">-</span> <span class="DecNumber">1</span><span class="Punctuation">)</span> <span class="Operator">+</span> <span class="Identifier">fib</span><span class="Punctuation">(</span><span class="Identifier">a</span> <span class="Operator">-</span> <span class="DecNumber">2</span><span class="Punctuation">)</span></pre></p>
  154. <p>Create a <tt class="docutils literal"><span class="pre">maths.c</span></tt> file with the following content:</p>
  155. <p><pre class="listing"><span class="Preprocessor">#include</span> <span class="Operator">&lt;</span><span class="Identifier">stdio</span><span class="Punctuation">.</span><span class="Identifier">h</span><span class="Operator">&gt;</span>
  156. <span class="Keyword">int</span> <span class="Identifier">fib</span><span class="Punctuation">(</span><span class="Keyword">int</span> <span class="Identifier">a</span><span class="Punctuation">)</span><span class="Punctuation">;</span>
  157. <span class="Keyword">void</span> <span class="Identifier">NimMain</span><span class="Punctuation">(</span><span class="Punctuation">)</span><span class="Punctuation">;</span>
  158. <span class="Keyword">int</span> <span class="Identifier">main</span><span class="Punctuation">(</span><span class="Keyword">void</span><span class="Punctuation">)</span>
  159. <span class="Punctuation">{</span>
  160. <span class="Identifier">NimMain</span><span class="Punctuation">(</span><span class="Punctuation">)</span><span class="Punctuation">;</span>
  161. <span class="Keyword">for</span> <span class="Punctuation">(</span><span class="Keyword">int</span> <span class="Identifier">f</span> <span class="Operator">=</span> <span class="DecNumber">0</span><span class="Punctuation">;</span> <span class="Identifier">f</span> <span class="Operator">&lt;</span> <span class="DecNumber">10</span><span class="Punctuation">;</span> <span class="Identifier">f</span><span class="Operator">++</span><span class="Punctuation">)</span>
  162. <span class="Identifier">printf</span><span class="Punctuation">(</span><span class="StringLit">&quot;Fib of %d is %d</span><span class="EscapeSequence">\n</span><span class="StringLit">&quot;</span><span class="Punctuation">,</span> <span class="Identifier">f</span><span class="Punctuation">,</span> <span class="Identifier">fib</span><span class="Punctuation">(</span><span class="Identifier">f</span><span class="Punctuation">)</span><span class="Punctuation">)</span><span class="Punctuation">;</span>
  163. <span class="Keyword">return</span> <span class="DecNumber">0</span><span class="Punctuation">;</span>
  164. <span class="Punctuation">}</span></pre></p>
  165. <p>Now you can run the following Unix like commands to first generate C sources from the Nim code, then link them into a static binary along your main C program:</p>
  166. <p><pre class="listing"><span class="program">nim</span> <span class="option">c</span> <span class="option">--noMain</span> <span class="option">--noLinking</span> <span class="Identifier">fib.nim</span>
  167. <span class="program">gcc</span> <span class="option">-o</span> <span class="option">m</span> <span class="Identifier">-I$HOME/.cache/nim/fib_d</span> <span class="Identifier">-Ipath/to/nim/lib</span> <span class="Identifier">$HOME/.cache/nim/fib_d/*.c</span> <span class="Identifier">maths.c</span></pre></p>
  168. <p>The first command runs the Nim compiler with three special options to avoid generating a <tt class="docutils literal"><span class="pre"><span class="Identifier">main</span><span class="Punctuation">(</span><span class="Punctuation">)</span></span></tt> function in the generated files and to avoid linking the object files into a final binary. All the generated files are placed into the <tt class="docutils literal"><span class="pre">nimcache</span></tt> directory. That's why the next command compiles the <tt class="docutils literal"><span class="pre">maths.c</span></tt> source plus all the <tt class="docutils literal"><span class="pre">.c</span></tt> files from <tt class="docutils literal"><span class="pre">nimcache</span></tt>. In addition to this path, you also have to tell the C compiler where to find Nim's <tt class="docutils literal"><span class="pre">nimbase.h</span></tt> header file.</p>
  169. <p>Instead of depending on the generation of the individual <tt class="docutils literal"><span class="pre">.c</span></tt> files you can also ask the Nim compiler to generate a statically linked library:</p>
  170. <p><pre class="listing"><span class="program">nim</span> <span class="option">c</span> <span class="option">--app:staticLib</span> <span class="Identifier">fib.nim</span>
  171. <span class="program">gcc</span> <span class="option">-o</span> <span class="option">m</span> <span class="option">-Inimcache</span> <span class="Identifier">-Ipath/to/nim/lib</span> <span class="Identifier">maths.c</span> <span class="Identifier">libfib.nim.a</span></pre></p>
  172. <p>The Nim compiler will handle linking the source files generated in the <tt class="docutils literal"><span class="pre">nimcache</span></tt> directory into the <tt class="docutils literal"><span class="pre">libfib.nim.a</span></tt> static library, which you can then link into your C program. Note that these commands are generic and will vary for each system. For instance, on Linux systems you will likely need to use <tt class="docutils literal"><span class="pre option">-ldl</span></tt> too to link in required dlopen functionality.</p>
  173. <h3><a class="toc-backref" id="backend-code-calling-nim-nim-invocation-example-from-javascript" href="#backend-code-calling-nim-nim-invocation-example-from-javascript">Nim invocation example from JavaScript</a></h3><p>Create a <tt class="docutils literal"><span class="pre">mhost.html</span></tt> file with the following content:</p>
  174. <p><pre class="listing">&lt;html&gt;&lt;body&gt;
  175. &lt;script type=&quot;text/javascript&quot; src=&quot;fib.js&quot;&gt;&lt;/script&gt;
  176. &lt;script type=&quot;text/javascript&quot;&gt;
  177. alert(&quot;Fib for 9 is &quot; + fib(9));
  178. &lt;/script&gt;
  179. &lt;/body&gt;&lt;/html&gt;</pre></p>
  180. <p>Create a <tt class="docutils literal"><span class="pre">fib.nim</span></tt> file with the following content (or reuse the one from the previous section):</p>
  181. <p><pre class="listing"><span class="Keyword">proc</span> <span class="Identifier">fib</span><span class="Punctuation">(</span><span class="Identifier">a</span><span class="Punctuation">:</span> <span class="Identifier">cint</span><span class="Punctuation">)</span><span class="Punctuation">:</span> <span class="Identifier">cint</span> <span class="Punctuation">{</span><span class="Operator">.</span><span class="Identifier">exportc</span><span class="Operator">.</span><span class="Punctuation">}</span> <span class="Operator">=</span>
  182. <span class="Keyword">if</span> <span class="Identifier">a</span> <span class="Operator">&lt;=</span> <span class="DecNumber">2</span><span class="Punctuation">:</span>
  183. <span class="Identifier">result</span> <span class="Operator">=</span> <span class="DecNumber">1</span>
  184. <span class="Keyword">else</span><span class="Punctuation">:</span>
  185. <span class="Identifier">result</span> <span class="Operator">=</span> <span class="Identifier">fib</span><span class="Punctuation">(</span><span class="Identifier">a</span> <span class="Operator">-</span> <span class="DecNumber">1</span><span class="Punctuation">)</span> <span class="Operator">+</span> <span class="Identifier">fib</span><span class="Punctuation">(</span><span class="Identifier">a</span> <span class="Operator">-</span> <span class="DecNumber">2</span><span class="Punctuation">)</span></pre></p>
  186. <p>Compile the Nim code to JavaScript with <tt class="docutils literal"><span class="pre"><span class="program">nim</span> <span class="option">js</span> <span class="Identifier">-o:fib.js</span> <span class="Identifier">fib.nim</span></span></tt> and open <tt class="docutils literal"><span class="pre">mhost.html</span></tt> in a browser. If the browser supports javascript, you should see an alert box displaying the text <tt class="docutils literal"><span class="pre">Fib for 9 is 34</span></tt>. As mentioned earlier, JavaScript doesn't require an initialization call to <tt class="docutils literal"><span class="pre"><span class="Identifier">NimMain</span></span></tt> or a similar function and you can call the exported Nim proc directly.</p>
  187. <h2><a class="toc-backref" id="interfacing-nimcache-naming-logic" href="#interfacing-nimcache-naming-logic">Nimcache naming logic</a></h2><p>The <span id="nimcache_1">nimcache</span> directory is generated during compilation and will hold either temporary or final files depending on your backend target. The default name for the directory depends on the used backend and on your OS but you can use the <tt class="docutils literal"><span class="pre option">--nimcache</span></tt> <a class="reference external" href=" nimc.html#compiler-usage-commandminusline-switches">compiler switch</a> to change it.</p>
  188. <h1><a class="toc-backref" id="memory-management" href="#memory-management">Memory management</a></h1><p>In the previous sections, the <tt class="docutils literal"><span class="pre"><span class="Identifier">NimMain</span><span class="Punctuation">(</span><span class="Punctuation">)</span></span></tt> function reared its head. Since JavaScript already provides automatic memory management, you can freely pass objects between the two languages without problems. In C and derivative languages you need to be careful about what you do and how you share memory. The previous examples only dealt with simple scalar values, but passing a Nim string to C, or reading back a C string in Nim already requires you to be aware of who controls what to avoid crashing.</p>
  189. <h2><a class="toc-backref" id="memory-management-strings-and-c-strings" href="#memory-management-strings-and-c-strings">Strings and C strings</a></h2><p>The manual mentions that <a class="reference external" href="manual.html#types-cstring-type">Nim strings are implicitly convertible to cstrings</a> which makes interaction usually painless. Most C functions accepting a Nim string converted to a <tt class="docutils literal"><span class="pre"><span class="Identifier">cstring</span></span></tt> will likely not need to keep this string around and by the time they return the string won't be needed anymore.</p>
  190. <p>A similar thing happens with C code invoking Nim code which returns a <tt class="docutils literal"><span class="pre"><span class="Identifier">cstring</span></span></tt>. Consider the following proc:</p>
  191. <p><pre class="listing"><span class="Keyword">proc</span> <span class="Identifier">gimme</span><span class="Punctuation">(</span><span class="Punctuation">)</span><span class="Punctuation">:</span> <span class="Identifier">cstring</span> <span class="Punctuation">{</span><span class="Operator">.</span><span class="Identifier">exportc</span><span class="Operator">.</span><span class="Punctuation">}</span> <span class="Operator">=</span>
  192. <span class="Identifier">result</span> <span class="Operator">=</span> <span class="StringLit">&quot;Hey there C code! &quot;</span> <span class="Operator">&amp;</span> <span class="Operator">$</span><span class="Identifier">rand</span><span class="Punctuation">(</span><span class="DecNumber">100</span><span class="Punctuation">)</span></pre></p>
  193. <p>Since Nim's reference counting mechanism is not aware of the C code, once the <tt class="docutils literal"><span class="pre"><span class="Identifier">gimme</span></span></tt> proc has finished it can reclaim the memory of the <tt class="docutils literal"><span class="pre"><span class="Identifier">cstring</span></span></tt>.</p>
  194. <h2><a class="toc-backref" id="memory-management-custom-data-types" href="#memory-management-custom-data-types">Custom data types</a></h2><p>Just like strings, custom data types that are to be shared between Nim and the backend will need careful consideration of who controls who. If you want to hand a Nim reference to C code, you will need to use <a class="reference external" href=" system.html#GC_ref,ref.T">GC_ref</a> to mark the reference as used, so it does not get freed. And for the C backend you will need to expose the <a class="reference external" href=" system.html#GC_unref,ref.T">GC_unref</a> proc to clean up this memory when it is not required anymore.</p>
  195. <p>Again, if you are wrapping a library which <em>mallocs</em> and <em>frees</em> data structures, you need to expose the appropriate <em>free</em> function to Nim so you can clean it up. And of course, once cleaned you should avoid accessing it from Nim (or C for that matter). Typically C data structures have their own <tt class="docutils literal"><span class="pre"><span class="Identifier">malloc_structure</span></span></tt> and <tt class="docutils literal"><span class="pre"><span class="Identifier">free_structure</span></span></tt> specific functions, so wrapping these for the Nim side should be enough. </p>
  196. </p>
  197. </div>
  198. </div>
  199. <div class="twelve-columns footer">
  200. <span class="nim-sprite"></span>
  201. <br>
  202. <small style="color: var(--hint);">Made with Nim. Generated: 2025-03-12 16:38:57 UTC</small>
  203. </div>
  204. </div>
  205. </div>
  206. <script defer data-domain="nim-lang.org" src="https://plausible.io/js/plausible.js"></script>
  207. </body>
  208. </html>