-
Notifications
You must be signed in to change notification settings - Fork 2
Module
Creating modules to use with CoreJS is relatively easy. Below will be a quick intro on creating a new class that will exposed to Javascript. Modules can be written in Javascript or C/C++.
###Javascript Module Example
// First we setup the name and method for our function:
var HelloWorld = function() {
print("Hello World")
};
// Now we export our method so we can require and use it later.
exports.HelloWorld = HelloWorld;Now to use this module in another script we use the require method with an absolute or relative path. using the designated extension ".cm" for Core Module.
// Requiring our module will return an object that contains our new method
var helloWorld = require("./path/to/HelloWorld");
// Once we have our object we can call our method
helloWorld.HelloWorld();
// We can also short hand this a bit using:
var hiWorld = require("./path/to/HelloWorld").HelloWorld;
hiWorld();###C/C++ Module Example
CoreJS supports C/C++ shared libraries for modules as well. The basics for creating a C/C++ shared library for use with CoreJS are pretty simple. CoreJS only requires one function in your module to allow it to load and use your module. Below is the basic skeleton for creating a shared library module for CoreJS.
#include <string>
#include <stdlib.h>
#include <stdio.h>
#include <v8.h>
using namespace std;
using namespace v8;
class MyMod
{
public:
static Handle<Value> HelloWorld(const Arguments &args)
{
HandleScope scope;
printf("\nHello World from compiled module");
return scope.Close(Undefined());
}
static void init(Handle<Object>exports)
{
HandleScope scope;
exports->Set(String::New("HelloWorld"), FunctionTemplate::New(HelloWorld)->GetFunction());
}
};
extern "C" void CoreInit(Handle<Object> exports)
{
MyMod::init(exports);
}
Once compiled and built, you can use this module the same as you would a javascript module. The following is an example of importing and using your compiled module in a Javascript file.
// It is required using relative or absolute path to the file.
// Which returns an object containing all classes/methods from your module.
var hi = require("/path/to/MyMod");
hi.HelloWorld();
// You can also short hand these to get right to what you want.
var hi = require("/path/to/MyMod").HelloWorld;
hi();As CoreJS continues to develop, tools will be created to make creating modules even simpler. Also if a module lives in a default environment or user path, only the name of the module is required when using Require method. ( require('module_name') ).