Skip to content

Instantly share code, notes, and snippets.

@yamachu
Created September 12, 2021 08:08
Show Gist options
  • Save yamachu/880a8d7d82095f7a3c0593ffbd373106 to your computer and use it in GitHub Desktop.
Save yamachu/880a8d7d82095f7a3c0593ffbd373106 to your computer and use it in GitHub Desktop.
https://github.com/yamachu/LibOpenJTalk をNode.jsから呼び出すやつの下書き
import { Library } from 'ffi-napi';
import ArrayType from 'ref-array-napi';
import {
alloc,
allocCString,
readCString,
refType,
sizeof,
types,
} from 'ref-napi';
// typedef
const typeofOpenJTalkInstance = types.void;
const typeofPtrOfOpenJTalkInstance = refType(typeofOpenJTalkInstance);
const intPtr = refType('int');
const stringPtr = refType('string');
const stringPtrPtr = refType(stringPtr);
const stringPtrArray = ArrayType(stringPtr);
// Open library once
const libopenjtalk = Library('libopenjtalk-lang', {
Open_JTalk_initialize: [typeofPtrOfOpenJTalkInstance, []],
Open_JTalk_clear: ['void', [typeofPtrOfOpenJTalkInstance]],
Open_JTalk_load_u16: ['int', [typeofPtrOfOpenJTalkInstance, 'string']],
Open_JTalk_extract_label_u16: [
'int',
[typeofPtrOfOpenJTalkInstance, 'string', stringPtrPtr, intPtr],
],
});
export const initialize = (dictPath: string) => {
const openjtalkInstancePointer = libopenjtalk.Open_JTalk_initialize();
if (openjtalkInstancePointer.isNull()) {
throw new Error('Cannot Initialize LibOpenJTalk');
}
const dictPathUnicode = allocCString(dictPath, 'utf16le');
const loaded =
libopenjtalk.Open_JTalk_load_u16(
openjtalkInstancePointer,
dictPathUnicode as any /* 型が合わないけど、文字コードを指定するにはこれ以外の方法が見当たらなかった */
) == 1;
dictPathUnicode.deref();
if (!loaded) {
libopenjtalk.Open_JTalk_clear(openjtalkInstancePointer);
throw new Error('Cannot Load dict');
}
return {
extractLabel: (text: string) => {
const refLengthInt = alloc('int');
const refStringPointer = alloc(stringPtrPtr);
const textUnicode = allocCString(text, 'utf16le');
const succeeded =
libopenjtalk.Open_JTalk_extract_label_u16(
openjtalkInstancePointer,
textUnicode as any,
refStringPointer,
refLengthInt as any
) === 1;
textUnicode.deref();
const labelArrayLength = refLengthInt.deref();
const labelsPointer = refStringPointer.deref();
const labelsPointerArray = new stringPtrArray(
labelsPointer.reinterpret(sizeof.pointer * labelArrayLength)
);
if (!succeeded) {
return [];
}
return [...Array(labelArrayLength)]
.map((_, i) => i)
.map((i) => readCString(labelsPointerArray[i] as any));
},
destroy: () => {
libopenjtalk.Open_JTalk_clear(openjtalkInstancePointer);
},
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment