前提、実現したいこと
npmのffi-napiを使ってdllをElectronで使おうとしています。
dllの一部関数は既に問題なく動いています。
問題点
dllの関数の引数でBYTE型を参照渡しするものがあり、ffi-napi、ref-napiの正しい使い方が分からず困っています。
- C#における引数の"out int outlength"をJavascriptでどう表すか分からない。ref.refType('int')??
- JavascriptにおけるBYTE型について分かっていない
問題のコード(一部抜粋)
main.ts
// ffi const ffi = require('ffi-napi'); const ref = require('ref-napi'); // ~~~~省略~~~~~ // eslint-disable-next-line prefer-const let outlength = ref.refType('int'); // eslint-disable-next-line prefer-const // let lpResponse = ref.refType('byte'); // \u0000SAMPLE_くらいまでで切れてしまう。サイズ不足? // eslint-disable-next-line prefer-const let lpResponse = ref.types.CString; const dllSample = ffi.Library(dllPath, { InitPort: ['int', ['int', 'int']], GetVersion: ['int', ['int', outlength, lpResponse]], }); // eslint-disable-next-line prefer-const let outlength2 = ref.alloc(outlength); // let outlength2 = ref.alloc('int'); // eslint-disable-next-line prefer-const let lpResponse2 = new Uint8Array(256); // let lpResponse2 = new ArrayBuffer(256); // eslint-disable-next-line prefer-const // let lpResponse3 = ref.alloc(lpResponse2); // TypeError: could not determine a proper "type" from: Uint8Array // eslint-disable-next-line prefer-const let lpResponse3 = ref.alloc(lpResponse); console.dir('lpResponse bef===>' + lpRes3); // 出力⇒'lpResponse bef===>\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000' const resGetVersion = dllSample.GetVersion(4, outlength2, lpResponse3); console.log('resGetVersion->' + resGetVersion); // console.dir('outlength2=>' + outlength2); // Err! 「Electronは終了しました」になる // console.log('lpResponse=>' + lpResponse3.deref()); //Err! 「Electronは終了しました」になる console.dir(String.fromCharCode(lpResponse3)); // 出力⇒'\u0000' console.dir(lpResponse3.toString()); // 出力⇒'\u0000SAMPLE_'
移行元のC#のコード(抜粋)
Class1.cs
namespace Sample { public class Class1 { [DllImport("Sample.dll")] public static extern int InitPort(int nPort, int nBaud); [DllImport("Sample.dll")] public static extern int GetVersion(int nPort, out int outlength, byte[] lpResponse); } }
Form1.cs
int outlength; byte[] lpResponse = new byte[256]; string strtmp; int ret; ret = Sample.Class1.GetVersion(4, out outlength, lpResponse); if (ret == 0) { strtmp = System.Text.Encoding.Default.GetString(lpResponse, 1, outlength - 1); this.textBox1.Text = strtmp; }
あなたの回答
tips
プレビュー