Thursday 27 February 2020

How to pass byte[] type variables to FFI imported DLL in nodeJS?

(xposted on StackOverFlow)Below is an excerpt csharp implementation of Wireguard client using the DLL. (https://github.com/WireGuard/wireguard-windows/tree/master/embeddable-dll-service)```csharp /* SPDX-License-Identifier: MIT * * Copyright (C) 2019 WireGuard LLC. All Rights Reserved. */using System; using System.Runtime.InteropServices;namespace Tunnel { public class Keypair { public readonly string Public; public readonly string Private; private Keypair(string pub, string priv) { Public = pub; Private = priv; } [DllImport("tunnel.dll", EntryPoint = "WireGuardGenerateKeypair", CallingConvention = CallingConvention.Cdecl)] private static extern bool WireGuardGenerateKeypair(byte[] publicKey, byte[] privateKey); public static Keypair Generate() { var publicKey = new byte[32]; var privateKey = new byte[32]; WireGuardGenerateKeypair(publicKey, privateKey); return new Keypair(Convert.ToBase64String(publicKey), Convert.ToBase64String(privateKey)); } } } ```Now I want to port this code to nodejs using the same DLL. I came so far from this sample project.```nodejs /* Node 10 and lower npm i ffi https://www.npmjs.com/package/ffi https://github.com/node-ffi/node-ffi Node 11 and higher npm i @saleae/ffi https://www.npmjs.com/package/@saleae/ffi https://github.com/lxe/node-ffi/tree/node-12 */// Import dependencies const ffi = require("@saleae/ffi");var ref = require('ref');// Convert JSString to CString function TEXT(text) { return Buffer.from(${text}\0, "ucs2"); }// Import tunnel const tunnel = new ffi.Library("wireguardfiles/tunnel", { "WireGuardGenerateKeypair": [ "bool", ["String", "String"] ] });var publickey = "string"; var privatekey = "string";var result = tunnel.WireGuardGenerateKeypair(publickey, privatekey)process.stdout.write(result); ```As you can see it is clearly wrong since I am using String instead of byte[]. This is because I got TypeError: could not determine a proper "type" from: byte[] error.Any idea on how to pass byte[] arguments to DLL from nodejs?Thank you!

Submitted February 27, 2020 at 09:16AM by shiskeyoffles

No comments:

Post a Comment