This article describes how to call a C language program from Electron using standard input/output. When calling a C language program, the spawn function included in the child_process, which is the standard library of Node.js, is called from the main process. The related resources are shown below.
The procedure is shown below.
- C language coding preparation
- C language coding
- C language build
- Electron coding preparation
- Electron coding
- Operation check
Run the following commands in your terminal to prepare for C language coding
mkdir electron-child-process
cd electron-child-process
touch add.c
Open add.c in your editor and enter the following content.
Run the following command in your terminal to build the C language source code.
gcc -o add add.c
Run the following commands in your terminal to prepare for Electron coding.
npm init -y
npm install --save-dev electron
touch index.html main.js
Open index.html in your editor and enter the following content.
Open main.js in your editor and enter the following content.
The points are shown below.
- Since it is necessary to wait for the exit of the child process, enclose the entire processing related to the spawn function in Promise.
- Call the spawn function to start the child process.
- Pipe the standard error output of the child process to the standard error output of the main process so that you can see the error messages when they are written to the standard error output of the child process.
- Add an event handler to the data event of the child process's standard output to get the output.
- Add an event handler in the exit event of the child process and wait for the exit. When the child process exits, the event handler is called with the exit code as an argument, so check that the exit code is 0 before resolving the promise.
- Add an event handler in the error event of the child process and reject the promise when a start error or execution error occurs.
Open package.json in your editor and change the main property as follows.
"main": "main.js",
Run the following command to start Electron.
npx electron .
Check that the execution result is the same as the following.
{"sum":"3"}
I don't have enough knowledge, but I think it would be difficult to create a Node.js native module in C and call it from Electron. On the other hand, standard I / O is easy to use, so I use this method. One of the advantages of this method is that it is easy to debug because the C language program can be started by itself. You can also replace the C language program later. On the other hand, one of the disadvantages is that there is an overhead in starting the child process, which reduces performance. In cases where you need to call handreds of times per second, it may be better to create a native module. If you have any opinions or impressions, please feel free to comment. Thank you for reading!