Created
October 1, 2012 02:47
-
-
Save TooTallNate/3809210 to your computer and use it in GitHub Desktop.
This gist has been moved to `ref-wchar` module on npm, see: https://github.com/TooTallNate/ref-wchar
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var ffi = require('ffi') | |
var ref = require('ref') | |
var assert = require('assert') | |
var wchar_t = require('./wchar_t') | |
// now we can create our FFI'd "wcslen()" function | |
var libc = ffi.Library('libc', { | |
wcslen: [ 'size_t', [ wchar_t ] ], | |
wcstod: [ 'double', [ wchar_t, ref.refType(wchar_t) ] ] | |
}) | |
// you pass regular JavaScript Strings to the FFI'd function and the "wchar_t" | |
// type we defined handles converting it to a proper Buffer behind the scenes. | |
assert.equal(5, libc.wcslen('hello')) | |
assert.equal(11, libc.wcslen('hello world')) | |
assert.equal(-3.14, libc.wcstod('-3.14', null)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Module dependencies. | |
*/ | |
var ref = require('ref') | |
var Iconv = require('iconv').Iconv | |
// vars used by the "wchar_t" type | |
var wchar_size, getter, setter | |
// On Windows they're UTF-16 (2-bytes), but on Unix platform they're UTF-32 | |
// (4-bytes). | |
if ('win32' == process.platform) { | |
wchar_size = 2 | |
getter = new Iconv('UTF-16' + ref.endianness, 'UTF-8') | |
setter = new Iconv('UTF-8', 'UTF-16' + ref.endianness) | |
} else { | |
wchar_size = 4 | |
getter = new Iconv('UTF-32' + ref.endianness, 'UTF-8') | |
setter = new Iconv('UTF-8', 'UTF-32' + ref.endianness) | |
} | |
// Create a "wchar_t *" type. We use the "CString" type as a base since it's pretty | |
// close to what we actually want. We just have to define custom "get" and "set" | |
// functions and then we can use this type in FFI functions. | |
var wchar_t = Object.create(ref.types.CString) | |
wchar_t.get = function get (buf, offset) { | |
var _buf = buf.readPointer(offset) | |
if (_buf.isNull()) { | |
return null | |
} | |
var stringBuf = _buf.reinterpretUntilZeros(wchar_size) | |
return getter.convert(stringBuf).toString('utf8') | |
}; | |
wchar_t.set = function set (buf, offset, val) { | |
var _buf = val // val is a Buffer? it better be \0 terminated... | |
if ('string' == typeof val) { | |
_buf = setter.convert(val + '\0') | |
} | |
return buf.writePointer(_buf, offset) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this gist has been moved to
ref-wchar
module on npmSee: https://github.com/TooTallNate/ref-wchar