Using and writing loadable modules

Previous: "Without macros please"

Loading a module - and using it - is easy:

let posix = require('posix')
posix.sleep(5);

To load modules in directories that aren't searched by default, you can do the following:

require.paths.push('/my/directory');
require('somemodule');

And you can also write your own modules. Either by simply putting a file named <module-name>.js in a directory in require.paths - or, more relevant to this tutorial, by compiling a shared object or dynamic library (the name pattern is lib<module-name>.so, lib<module-name>.dylib <module-name>.dll here).

#include <flusspferd.hpp>
#include <iostream>
#include <ostream>

void do_nothing_useful() {
    std::cout << "Yup, this is a function that does nothing useful." << std::endl;
}

FLUSSPFERD_LOADER_SIMPLE(exports) {
    flusspferd::create<flusspferd::function>(
        "doNothingUseful", &do_nothing_useful,
        flusspferd::param::_container = exports);
    exports.set_property("variable", true);
    std::cout << "Module loaded!" << std::endl;
}
Note:
You can find this module in help/examples/dummy_module.cpp.

If you compile this module as a shared library with the name libdummy_module.so or libmodule_dummy.dylib, you should be able to load it from the flusspferd shell.

> require.paths.push('/my/directory')
2
> require('dummy_module')
Module loaded!
(require('dummy_module'))
> mod = require('dummy_module')
(require('dummy_module'))
> mod.doNothingUseful()
Yup, this is a function that does nothing useful.
> mod.variable
true
See also:
SecurableModules, which is the foundation of Flusspferd's module support.

Next: Compiling C++ modules


Contact us at team -AT- flusspferd -DOT- org or as described on our homepage.

Generated on Thu Feb 4 23:05:12 2010 for Flusspferd by doxygen 1.6.1