node-ffiが先日v1.3.0になり、nodejsのv0.11, v0.12に対応し、nanパッケージも使用するようになりました。
詳しい内容は、node-ffiのリポジトリのHistory.mdを読むといいです。
node-ffi/History.md at master · node-ffi/node-ffi
早速atom-shellで試してみます。
環境
Ubuntu 14.10
環境による差異は、主にネイティブモジュールのビルドだと思うので、node-ffiのexampleを参考にOSにあったビルド方法を選択することにより、多分他のOSでも試せます。
node-ffi/example/factorial at master · node-ffi/node-ffi
インストール
現行のatom-shellで使用しているnodejsのバージョンは、iojs-v1.5.1です。
nvmなり、nodebrewで環境を作ります。
$ nvm install iojs-v1.5.1
atom-shellとnode-ffiを入れます。
$ npm init
$ npm install atom-shell ffi -save
サンプルコード
ディレクトリ構成
├── index.html
├── index.js
├── native
│ ├── libSay.c
│ ├── libSay.h
│ └── libSay.so
├── node_modules/
└── package.json
atom-shellのエントリポイント
index.js
var app = require('app');
var BrowserWindow = require('browser-window');
require('crash-reporter').start();
var mainWindow = null;
app.on('ready', function() {
mainWindow = new BrowserWindow({width: 800, height: 600});
mainWindow.loadUrl('file://' + __dirname + '/index.html');
mainWindow.on('closed', function() {
mainWindow = null;
});
});
UI(html)
index.html
<!DOCTYPE html>
<html>
<head>
<title>Hello atom-shell with ffi!</title>
</head>
<body>
<h1>Hello atom-shell with ffi!</h1>
We are using io.js <script>document.write(process.version)</script><br />
and atom-shell <script>document.write(process.versions['atom-shell'])</script>.
<script>
var ffi = require('ffi');
document.write('<h2>Example: Readme</h2>');
var libm = ffi.Library('libm', {
'ceil': [ 'double', [ 'double' ] ]
});
document.write('<div>"libm" sample: ' + libm.ceil(1.5) + '</div>'); // 2
// You can also access just functions in the current process by passing a null
var current = ffi.Library(null, {
'atoi': [ 'int', [ 'string' ] ]
});
document.write('<div>"atoi" sample: ' + current.atoi('1234') + '</div>'); // 1234
document.write('<h2>Example native module(C language)</h2>');
var say = ffi.Library('./native/libSay.so', {
'hello': [ 'string', [ ] ],
'echo': [ 'string', [ 'string' ] ]
});
document.write('<div>' + say.hello() + '</div>'); // Hello!
document.write('<div>' + say.echo('World!') + '</div>'); // World!
</script>
</body>
</html>
ネイティブモジュール(C言語)
libSay.h
#ifndef __LIB_SAY_H
#define __LIB_SAY_H
char* echo(char* word);
char* hello();
#endif
libSay.c
#include "libSay.h"
char* echo(char* word) {
return word;
}
char* hello() {
return (char*)"Hello!";
}
ネイティブモジュールのビルドです。
$ gcc -shared -fpic libSay.c -o libSay.co
結果
無事動きました。