Code Monkey home page Code Monkey logo

puerts_node's Introduction

Puerts Node.js Addon: High-Performance Bridge between C++ and JavaScript

Welcome to our Node.js addon, powered by Puerts. This high-performance tool allows you to bind C++ functions and classes to the V8 JavaScript engine, enabling seamless and efficient use of C++ code in your JavaScript environment.

Installation

You can install puerts using npm:

npm install -g puerts

Example

C++ code to be call

class HelloWorld
{
public:
    HelloWorld(int p) {
        Field = p;
    }

    void Foo(std::function<bool(int, int)> cmp) {
        bool ret = cmp(Field, StaticField);
        std::cout << "Foo, Field: " << Field << ", StaticField: " << StaticField << ", compare result:" << ret << std::endl;
    }
    
    static int Bar(std::string str) {
        std::cout << "Bar, str:" << str << std::endl;
        return  StaticField + 1;
    }
    
    int Field;
    
    static int StaticField;
};

int HelloWorld::StaticField = 0;

Export C++ API

UsingCppType(HelloWorld);

void Init() {
    puerts::DefineClass<HelloWorld>()
        .Constructor<int>()
        .Method("Foo", MakeFunction(&HelloWorld::Foo))
        .Function("Bar", MakeFunction(&HelloWorld::Bar))
        .Property("Field", MakeProperty(&HelloWorld::Field))
        .Variable("StaticField", MakeVariable(&HelloWorld::StaticField))
        .Register();
}

//hello_world is module name, will use in js later.
PESAPI_MODULE(hello_world, Init)

ps: Above C++ example project can be generate by below command line:

puerts init hello_world

Compile the generated addon project:

cd hello_world
mkdir build
cd build
cmake ..
cmake --build . --config Release

Calling addon in JavaScript

const puerts = require("puerts");

let hello_world = puerts.load('path/to/hello_world');
const HelloWorld = hello_world.HelloWorld;

const obj = new HelloWorld(101);
obj.Foo((x, y) => x > y);

HelloWorld.Bar("hello");

HelloWorld.StaticField = 999;
obj.Field = 888;
obj.Foo((x, y) => x > y);

TypeScript support

Generate typescript declaration file (index.d.ts) for a puerts addon

puerts gen_dts path\to\hello_world -t typing

Add typing directory to tsconfig.json/compilerOptions/typeRoots.

Calling addon in TypeScript

import {load} from "puerts";
import * as HelloWorldModlue from 'hello_world'

let hello_world = load<typeof HelloWorldModlue>('path/to/hello_world');

const HelloWorld = hello_world.HelloWorld;

const obj = new HelloWorld(101);

obj.Foo((x, y) => x > y);

HelloWorld.Bar("hello");

HelloWorld.StaticField = 999;
obj.Field = 888;

obj.Foo((x, y) => x > y);

Function & constructor overloading

class TestClass : public BaseClass
{
public:
	TestClass();
	
	TestClass(int32_t InX, int32_t InY);


	static void Overload();

	static void Overload(std::string a, int32_t b);

	int32_t OverloadMethod();

	int32_t OverloadMethod(int32_t a);
};
puerts::DefineClass<TestClass>()
    .Extends<BaseClass>()
    .Constructor(CombineConstructors(
        MakeConstructor(TestClass, int32_t, int32_t),
        MakeConstructor(TestClass)
        ))
    .Function("Overload", CombineOverloads(
        MakeOverload(void(*)(), &TestClass::Overload),
        MakeOverload(void(*)(std::string, int32_t), &TestClass::Overload)
        ))
    .Method("OverloadMethod", CombineOverloads(
        MakeOverload(int32_t(TestClass::*)(), &TestClass::OverloadMethod),
        MakeOverload(int32_t(TestClass::*)(int32_t), &TestClass::OverloadMethod)
        ))
    .Register();

Features

The following C++ features are supported: constructors, inheritance, member variables, member functions, static functions, static variables, function overloading (constructors/static functions/member functions)

Supports the generation of TypeScript declarations

For more examples, see: https://github.com/puerts/puerts_addon_demos

Performance

If you want to achieve higher performance, please add the PES_EXTENSION_WITH_V8_API macro during compilation. If you want to achieve the highest performance, add an additional WITH_V8_FAST_CALL and include the --turbo-fast-api-calls parameter when starting Node.js. For performance test data, please see here.

puerts_node's People

Contributors

chexiongsheng avatar

Stargazers

 avatar 南柯太守 avatar enfpdev avatar  avatar  avatar sixian kwan avatar 元极 avatar  avatar BlurryLight avatar AlexAnder avatar  avatar  avatar ARNO avatar

Watchers

 avatar

puerts_node's Issues

多dll相互调用如何在前端实现交互?

新建第一个模块,Test,新建一个c++类,Test,导出为Test.dll,code如下:

#pragma once
#include
#include

// Shared library support
#ifdef WIN32
#define EEXPORT __declspec(dllexport)
#define EIMPORT __declspec(dllimport)
#else
#define EEXPORT
#define EIMPORT
#endif

#ifdef TEST_EXPORTS
#define TEST_API EEXPORT
#else
#define TEST_API EIMPORT
#endif

class TEST_API Test
{
public:
Test() { std::cout << "Test()" << std::endl; }
};

新建第二个模块,Test2,新建一个C++类,Test2,依赖第一个模块,导出为Test2.dll,code如下:

.h
#pragma once
#include "Test.h"
class Test2
{
public:
Test2() { Test test; std::cout << "Test2" << std::endl; }

};

.cpp
#include <pesapi.h>
#include
#include <Binding.hpp>
#include "Test2.h"

UsingCppType(Test2);
void Init() {
puerts::DefineClass()
.Constructor()
.Register();
}

PESAPI_MODULE(Test2, Init)

node测试js Test.dll和Test2.dll都在Bin目录下:

const puerts = require("puerts");

let Test2Object = puerts.load('../Output/Bin/Test2');
const Testobject = Test2Object.Test2;
const obj = new Testobject();

报错信息:
Error: dlopen fail for ..\Output\Bin\Test2.dll, error: Win32 error 126
at Object.load (E:\code\PIE-Cloud\PIE-Earth\PIE-Earth-SDK\PIE-Earth\jni\Runtime\PIEEarth-NodeJS\node_modules\puerts\lib\puerts_node.js:28:38)
at Object. (E:\code\PIE-Cloud\PIE-Earth\PIE-Earth-SDK\PIE-Earth\jni\Runtime\PIEEarth-NodeJS\js\test.js:4:26)
at Module._compile (node:internal/modules/cjs/loader:1256:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
at Module.load (node:internal/modules/cjs/loader:1119:32)
at Module._load (node:internal/modules/cjs/loader:960:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:86:12)
at node:internal/main/run_main_module:23:47

How to Pass TypeScript Number Array to C++?

Hello,

I am currently working on a project where I need to pass an array of numbers from TypeScript to C++. I couldn't find any clear documentation or examples related to this.

typescript:
let numArray: number[] = [0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5 ];

cpp:
std::vector parser(std::vector input){
for (int i = 0; i < input.size(); i++)
{
input[i]++;
}
return input;
}

I would like to know how I can pass this numArray to a C++ function and access its elements.

Questions:
Is there any recommended method to do this?
Are there any data type constraints or considerations I should be aware of while passing the array?
Any guidance or reference to documentation would be greatly appreciated. Thank you in advance!

研究了下回调函数绑定部分,似乎是强转函数类型的,不会有安全性问题么?

研究了下回调函数绑定部分,pesapi部分的,似乎是强转函数类型的,
V8的回调函数类型是void (*)(const FunctionCallbackInfo& info)
pesapi接口用的类型是void (*pesapi_callback)(pesapi_callback_info info) pesapi_callback_info 是个指针类型
从参数为指针的函数类型强转为参数为引用的函数类型,调用的时候似乎是个未定义行为,不会有安全性问题么?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.