nodejs与c语言深度交互
Posted dong1
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了nodejs与c语言深度交互相关的知识,希望对你有一定的参考价值。
2、node-ffi
1)nodejs从c语言读取数据
factorial.c
#include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #if defined(WIN32) || defined(_WIN32) #define EXPORT __declspec(dllexport) #else #define EXPORT #endif typedef struct { double lon; double lat; }gps_info_t; gps_info_t* gps; void get_gps_shm_init(void) { gps = (gps_info_t *)malloc(sizeof(gps_info_t)); } EXPORT gps_info_t* get_gps_info(void) { get_gps_shm_init(); gps->lon = 55.5; gps->lat = 55.5;return gps; }
factorial.js
var ffi = require(‘../node-ffi-master/‘) var refStruct = require(‘ref-struct‘); var refArray = require(‘ref-array‘); var ref = require(‘ref‘); //gps date struct var gps = refStruct({ ‘lon‘:ref.types.double, ‘lat‘:ref.types.double, }); var gpsStructArrayType = refArray(gps); var gps_info = gpsStructArrayType(10); var libfactorial = ffi.Library(‘./libfactorial‘, { ‘get_gps_info‘: [ gpsStructArrayType, [ ‘void‘ ] ], }); gps_info = libfactorial.get_gps_info(0) console.log(‘Your output: ‘ + gps_info[0].lon) console.log(‘Your output: ‘ + gps_info[0].lat)
2)nodejs向c语言写数据
factorial.c
#include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #if defined(WIN32) || defined(_WIN32) #define EXPORT __declspec(dllexport) #else #define EXPORT #endif typedef struct { char *user_name; char *passwd; char *dev_id; }user_info_t; user_info_t* user; void put_user_info_shm_init(void) { user = (user_info_t *)malloc(sizeof(user_info_t)); user->user_name = (char*)malloc(32*sizeof(char)); user->passwd = (char*)malloc(32*sizeof(char)); user->dev_id = (char*)malloc(32*sizeof(char)); } EXPORT void put_user_info(user_info_t* user_info) { put_user_info_shm_init(); printf("get userinfo(user_name):%s",user_info->user_name); printf("get userinfo(user_name):%s",user_info->passwd); printf("get userinfo(user_name):%s",user_info->dev_id); }
factorial.js
var ffi = require(‘../node-ffi-master/‘) var refStruct = require(‘ref-struct‘); var refArray = require(‘ref-array‘); var ref = require(‘ref‘); //ui date struct var user = refStruct({ ‘user_name‘:‘string‘, ‘passwd‘:‘string‘, ‘dev_id‘:‘string‘, }); var userStructArrayType = refArray(user); var user_info = userStructArrayType(1); user_info[0].user_name = ‘zdd‘; user_info[0].passwd = ‘123‘; user_info[0].dev_id = ‘65535‘; var libfactorial = ffi.Library(‘./libfactorial‘, { ‘put_user_info‘: [ ‘void‘, [ userStructArrayType ] ] }); libfactorial.put_user_info(user_info) console.log(‘Your input: ‘ + user_info[0].user_name) console.log(‘Your input: ‘ + user_info[0].passwd) console.log(‘Your input: ‘ + user_info[0].dev_id)
以上是关于nodejs与c语言深度交互的主要内容,如果未能解决你的问题,请参考以下文章