mirror of
https://github.com/nim-lang/Nim.git
synced 2026-02-14 23:33:28 +00:00
Adds nimrod to backend examples.
This commit is contained in:
@@ -141,9 +141,75 @@ To wrap native code, take a look at the `c2nim tool <c2nim.html>`_ which helps
|
||||
with the process of scanning and transforming header files into a Nimrod
|
||||
interface.
|
||||
|
||||
Example in C.
|
||||
C invocation example
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Example in JS.
|
||||
Create a ``logic.c`` file with the following content:
|
||||
|
||||
.. code-block:: c
|
||||
int addTwoIntegers(int a, int b)
|
||||
{
|
||||
return a + b;
|
||||
}
|
||||
|
||||
Create a ``calculator.nim`` file with the following content:
|
||||
|
||||
.. code-block:: nimrod
|
||||
|
||||
{.compile: "logic.c".}
|
||||
proc addTwoIntegers(a, b: int): int {.importc.}
|
||||
|
||||
when isMainModule:
|
||||
echo addTwoIntegers(3, 7)
|
||||
|
||||
With these two files in place, you can run ``nimrod c -r calculator.nim`` and
|
||||
the Nimrod compiler will compile the ``logic.c`` file in addition to
|
||||
``calculator.nim`` and link both into an executable, which outputs ``10`` when
|
||||
run. Another way to link the C file statically and get the same effect would
|
||||
be remove the line with the ``compile`` pragma and run the following typical
|
||||
Unix commands::
|
||||
|
||||
$ gcc -c logic.c
|
||||
$ ar rvs mylib.a logic.o
|
||||
$ nimrod c --passL:mylib.a -r calculator.nim
|
||||
|
||||
Just like in this example we pass the path to the ``mylib.a`` library (and we
|
||||
could as well pass ``logic.o``) we could be passing switches to link any other
|
||||
static C library.
|
||||
|
||||
|
||||
JavaScript invocation example
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Create a ``host.html`` file with the following content:
|
||||
|
||||
.. code-block::
|
||||
|
||||
<html><body>
|
||||
<script type="text/javascript">
|
||||
function addTwoIntegers(a, b)
|
||||
{
|
||||
return a + b;
|
||||
}
|
||||
</script>
|
||||
<script type="text/javascript" src="calculator.js"></script>
|
||||
</body></html>
|
||||
|
||||
Create a ``calculator.nim`` file with the following content (or reuse the one
|
||||
from the previous section):
|
||||
|
||||
.. code-block:: nimrod
|
||||
|
||||
proc addTwoIntegers(a, b: int): int {.importc.}
|
||||
|
||||
when isMainModule:
|
||||
echo addTwoIntegers(3, 7)
|
||||
|
||||
Compile the Nimrod code to JavaScript with ``nimrod js -o:calculator.js
|
||||
calculator.nim`` and open ``host.html`` in a browser. If the browser supports
|
||||
javascript, you should see the value ``10``. In JavaScript the `echo proc
|
||||
<system.html#echo>`_ will modify the HTML DOM and append the string. Use the
|
||||
`dom module <dom.html>`_ for specific DOM querying and modification procs.
|
||||
|
||||
|
||||
Backend code calling Nimrod
|
||||
|
||||
Reference in New Issue
Block a user