Discovering the precise native memory address within electron with node-ffi-napi

By directly using Node.js, I am able to retrieve the correct native memory address as shown in the example below:

// For example, with a native DLL written in Rust. This portion can also be implemented in C or C++.
#[no_mangle]
pub unsafe extern fn example_concat(
  a: *const c_char,
  b: *const c_char
) -> *mut c_char
{
  let sa = CStr::from_ptr(a).to_str().expect("cannot convert a to str");
  let sb = CStr::from_ptr(b).to_str().expect("cannot convert b to str");
  let sr = format!("{}{}", sa, sb);
  let cr = CString::new(sr).expect("cannot create cr from sr");
  println!("[from native lib] cr={} *=0x{:X}", cr.to_str().expect("cannot convert cr to str"), cr.as_ptr() as c_ulonglong);
  cr.into_raw()
}
// tester.js
// Example using ffi and ref module in Node.js
const ffi = require('ffi-napi');
const ref = require('ref-napi');
const str = ref.types.CString;
const lib = ffi.Library( 'lib.dll', { 'example_concat': [ "char *", [ str, str ] ] } );
const buffer = lib.example_concat( "su", "shi" );
console.log( '[from tester.js]', buffer.hexAddress(), buffer.readCString() );

The output of running node tester.js would be something like this:

[from native lib] cr=sushi *=0x1E7B3B3E8C0
[from tester.js] 000001E7B3B3E8C0 sushi

However, when attempting a similar FFI approach with the react-electron system, issues arise.

// App.js within a React-Electron Node.js project
const remote = window.require('electron').remote;
const ffi = remote.require( 'ffi-napi' );
const ref = remote.require( 'ref-napi' );
const str = ref.types.CString;
const lib = ffi.Library( 'lib.dll', { 'example_concat': [ "char *", [ str, str ] ] } );
const buffer = lib.example_concat( "su", "shi" );
console.log( '[from App.js(electron)]', ref.hexAddress( buffer ), ref.readCString( buffer ) ); // <-- The memory address returned is incorrect!!

The result obtained from the electron version displays:

[from native lib] cr=sushi *=0x2BFA2F07A10
[from App.js(electron)] 000002BFA3BA7230 sushi

Any suggestions on how to obtain the accurate native memory address within an electron project?


  • Operating System: Microsoft Windows 10 (64-Bit) Version 10.0.19041.153
  • Node Version: 13.5.0
  • Node-ffi-napi Version: 2.4.7
  • Node-ffi-ref Version: 1.4.3
  • React Version: 16.13.0
  • Electron Version: 8.1.1

Answer №1

After carefully reviewing the situation at hand, I found a solution. By setting nodeIntegration: true in the posted scenario, I was able to successfully utilize the example involving

const remote = window.require('electron').remote
and remote.require. This allowed me to retrieve an address based on electron client through AddressForArgs(†1) using ref.HexAddress.

Subsequently, I decided to switch to nodeIntegration: false while incorporating the use of the preload feature.

// preload.js
window.ffi = require( 'ffi-napi' );
window.ref = require( 'ref-napi' );
// App.js (Modified for compatibility with the preload feature)
// const remote = window.require('electron').remote;
const ffi = window.ffi; //remote.require( 'ffi-napi' );
const ref = window.ref; //remote.require( 'ref-napi' );

As a result, everything started functioning as expected! A job well done, congratulations to myself!!

(†1): https://github.com/node-ffi-napi/ref-napi/blob/ed19a20370394b0b1914566f4ea9b5354b475732/src/binding.cc#L72

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Node.js JSON parser encountering an unexpected undefined error

Whenever I attempt to JSON.parse the string, an error occurs and I receive this message: undefined:1 {"device":"FaclonTest","data":[{"tag":"LATITUDE","value":1903.5091},{"tag":"LONGITUDE","value":07251.0348}]} I'm unsure of where the mistake is. Can ...

Steps to utilize the POST method with Angular, NodeJs/ExpressJs, and MySQL:

I am facing an issue with my Angular project where the GET method works fine, but when I try to call the POST method it seems like the POST function in Node.js is not getting called. Can someone help me figure out what I am doing wrong? Below are the snip ...

My goal was to alter the output for an array of objects

I needed to adjust the output for an array of objects. Here is my current result. I am looking to convert it into a specific format. let result = [ { team_id: 1, team_name: 'Avengers', participant1: 98, participant2: 99, par ...

The function `socket.broadcast.to(roomId).emit('xxxxxx', data)` is not functioning as expected on the client side

Frontend code: var app = angular.module("chatApp", ['btford.socket-io']); app.factory('socket', function (socketFactory) { return socketFactory({ prefix: '', ioSocket: io.connect(&ap ...

DynamoDB allows you to set a Time to Live (TTL) for items, displaying the expiration time but not automatically

My setup includes setting ttl as a TTL column and adding epoch time on it for certain items. https://i.stack.imgur.com/LenXa.png However, I noticed that these items are not being deleted. What could be causing this issue? https://i.stack.imgur.com/icEsl ...

Utilizing Vue.js to connect with a Node.js server

After setting up a basic Node.js server, the following code is running successfully: var http = require('http'); var server = http.createServer(); server.on('request', function(req, res) { res.writeHead(200, { 'content ...

Automated Database Testing: Streamlining Your Testing Process

As someone who is just starting out with automated testing, I've been thinking about the best approach to write tests for my database. The project I'm currently involved in utilizes PostgreSQL with Sequelize as the ORM on a Node.JS platform. Addi ...

Using NodeJS to convert a Base64 string into a JPEG image with the help of either NodeJS or

I have successfully stored a JPEG image in my MySQL database using the longblob format. Now, when I retrieve the longblob data, I am only getting a base64 string. How can I convert this base64 string back to a readable JPEG image using MySQL or Node.js? B ...

Tell me about node-persist

During my online learning journey of Node.js on Udemy, I encountered the term node-persist. Despite searching for it on Google, I couldn't find a clear explanation. Could someone please provide a concise definition of what node-persist is? ...

I encounter the error message "Class extends value undefined is not a constructor or null" in sveltekit when attempting to import a function from npm modules that I previously exported

I am struggling to send emails using SvelteKit and the "nodemailer" npm module. However, when I try to import the function, I encounter an error: "Class extends value undefined is not a constructor or null" Here is the code snippet from my mail.js file: i ...

What are the security benefits of using Res.cookie compared to document.cookie?

When it comes to setting cookies to save data of signed in members, I faced a dilemma between two options. On one hand, there's res.cookie which utilizes the Express framework to set/read cookies on the server-side. On the other hand, there's d ...

A guide on utilizing multer-sftp for downloading files

I've been working on this code, but after searching online I still haven't found a way to download a file from the remote server. I can successfully upload files to the server, but downloading them is posing a challenge. var storage = sftpStorag ...

Difficulties Encountered when Converting HTML to PDF with Puppeteer on AWS Lambda

HTML TO PDF Struggling with the conversion of HTML to PDF using Puppeteer in a Node.js 16 AWS Lambda environment is proving to be quite challenging. Puppeteer's performance seems to vary when deployed on AWS Lambda or serverless setups, despite work ...

Reaching out to a particular individual with a message

In my coding dilemma, I am trying to make a bot send a message every minute to a particular user, not all users. The struggle is real! guild.members.cache.forEach(member => { setInterval(() => { member.send('hello').catch(error =&g ...

Having trouble with installing npm packages? The node-gyp has encountered an end of line error while scanning the common.gypi

As I try to fetch dependencies for my React app using npm i, I encounter the following error: gyp info spawn args 'build', npm ERR! gyp info spawn args '-Goutput_dir=.' npm ERR! gyp info spawn args ] npm ERR! Traceback (most recent ...

Sanitizing form fields in node.js: Best practices and techniques

I recently installed the express-validator package to help me sanitize form fields. However, when I tried using it, I encountered an error: TypeError: req.sanitize is not a function. var express = require('express'); var router = express.Router() ...

The Android build for the Ionic package failed because of a TypeError: The property 'length' cannot be read as it is undefined

After creating a demo ionic project using ionic start conference, I encountered an issue when trying to build the Android package. The error message displayed was TypeError: Cannot read property 'length' of undefined. Attempting to create anothe ...

What is the best way to send emails when a Node application exits

Is it possible to set up an email notification using nodemailer or a similar tool when Node exits? I've noticed that the 'onBeforeExit' event is only meant for synchronous tasks, so I'm looking for alternatives. Specifically, I'd l ...

Guide on how to retrieve Twitter Username and Profile Photo through the Twit NPM Package

Utilizing the twit npm package to retrieve the Authenticated Twitter Username and Profile Image, here is the code I am using: const Twit = require('twit'); let T = new Twit({ consumer_key: 'xxx', ...

How to ensure NodeJS waits for a response before returning a value

I've come across a seemingly simple problem that I just can't seem to solve. My current project involves working with an asynchronous messaging bot. In this particular scenario, the bot is supposed to react to an event by calling a Restful API a ...