Compile your JavaScript

Calling C++ libraries in JavaScript with FFI in NectarJS

 

NectarJS is still a Work In Progress, nevertheless, we hear the community and we add functionalities that you need.

One month ago, an issue was created on the NectarJS Repo, asking for the possibility of an FFI capability in NectarJS : Issue #57

Regarding the numbers of C++ libs, it’s definitly worth it to add such a thing.

 

Adding an FFI module

 

This is how it works :

  • First, create a new module (a new folder with an index.js file in it in the nectar_modules folder of your project)
  • in this module, create a lib folder in which we will add our C++ lib, for example, test.cpp
  • at the top of your index.js file, add this : //!_ffi_include “lib/test.cpp”
  • Then, use your ffi function in your index.js

 

test.cpp:

 

// FFI example
#ifdef _WIN32
    #include "windows.h"
#endif


var __FFI_SIMPLE_MSGBOX()
{
	#ifdef _WIN32
		int msgboxID = MessageBox(NULL, "A simple messagebox", "Nectar FFI", MB_YESNOCANCEL);
	#else 
		cout << "this platform is not compatible with MessageBox" << "\n";
	#endif
	return var();
};


__NJS_FUNCTION_MACRO<var (var _message, var _title)> __WIN_MESSAGE_BOX   = [&](var _message, var _title) -> var
{
	#ifdef _WIN32
		int msgboxID = MessageBox(NULL, __NJS_GET_STRING(_message), __NJS_GET_STRING(_title), MB_ICONWARNING | MB_YESNOCANCEL);
	#else 
		cout << "this platform is not compatible with MessageBox" << "\n";
	#endif
	return var();
};


var ffiMsgBox = __NJS_CREATE_FUNCTION(&__WIN_MESSAGE_BOX);

 

index.js:

 

//!_ffi_include "lib/test.cpp"


var ffi = {
	msgBox: ffiMsgBox,
}


module.exports = ffi;

 

Then, call and use your new module in a test.js file in the root of your project:

 

var _ffi = require("test");


__FFI_SIMPLE_MSGBOX();


_ffi.msgBox("Hello !", "Nectar");


 

Compile and run your program, the message box should appear :

 

nectar --run test.js

 

Photo credits: Roman Synkevych

es_ESEspañol
en_USEnglish es_ESEspañol