@@ -297,7 +297,59 @@ Next, let’s try Python!
297
297
298
298
# Python
299
299
300
+ Create an ` embed.py` file in this directory, and put this in it:
301
+
302
+ ` ` ` python
303
+ from ctypes import cdll
304
+
305
+ lib = cdll.LoadLibrary(" target/release/libembed.so" )
306
+
307
+ lib.process()
308
+
309
+ print(" done! " )
310
+ ` ` `
311
+
312
+ Even easier! We use ` cdll` from the ` ctypes` module. A quick call
313
+ to ` LoadLibrary` later, and we can call ` process()` .
314
+
315
+ On my system, this takes ` 0.017` seconds. Speedy!
316
+
300
317
# Node.js
301
318
302
319
Node isn’t a language, but it’s currently the dominant implementation of
303
320
server-side JavaScript.
321
+
322
+ In order to do FFI with Node, we first need to install the library:
323
+
324
+ ` ` ` bash
325
+ $ npm install ffi
326
+ ` ` `
327
+
328
+ After that installs, we can use it:
329
+
330
+ ` ` ` javascript
331
+ var ffi = require('ffi');
332
+
333
+ var lib = ffi.Library('target/release/libembed', {
334
+ 'process': [ 'void', [] ]
335
+ });
336
+
337
+ lib.process();
338
+
339
+ console.log(" done! " );
340
+ ` ` `
341
+
342
+ It looks more like the Ruby example than the Python example. We use
343
+ the ` ffi` module to get access to ` ffi.Library()` , which loads up
344
+ our shared object. We need to annotate the return type and argument
345
+ types of the function, which are ' void' for return, and an empty
346
+ array to signify no arguments. From there, we just call it and
347
+ print the result.
348
+
349
+ On my system, this takes a quick ` 0.092` seconds.
350
+
351
+ # Conclusion
352
+
353
+ As you can see, the basics of doing this are _very_ easy. Of course,
354
+ there' s a lot more that we could do here. Check out the [FFI][ffi]
355
+ chapter for more details.
0 commit comments