0

I have a C++ project that is intended to perform some calculations. The C++ code will sit on a server that as back end to a browser based GUI. Node.js seems to be suitable for this job. I've gone through the tutorials and learnt to build C++ code to be used as a nodejs module.

For the sake of simplicity, I'd like to compile the C++ code as a static library. I could then write a C++ class which references this library which can then be used in the nodejs environment. The point of this is so I don't have to use node-gyp build to build my entire C++ project. This way I can further develop the C++ code without worrying too much about the front end.

To achieve this, I have done the following:

  1. Built a simple C++ library as follows. Building this in Visual Studio 2013 to get the .lib file.

    //MyClass.h
    #pragma once
    class MyClass
    {
    public:
        double Multiply(double a, double b)
        {
            return a*b;
        }
        MyClass();
        ~MyClass();
    };
    
  2. Created the C++ object to be used as a nodejs module like so:

    // myobject.h
    #ifndef MYOBJECT_H
    #define MYOBJECT_H
    
    #include <node.h>
    #include <node_object_wrap.h>
    #include "MyLib\MyClass.h"
    
    namespace demo {
    
        class MyObject : public node::ObjectWrap {
        public:
            static void Init(v8::Local<v8::Object> exports);
            static MyClass* mycalcobj;
    
        private:
            explicit MyObject(double value = 0);
            ~MyObject();
    
            static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
            static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);
            static v8::Persistent<v8::Function> constructor;
            double value_;
    
    
        };
    
    }  // namespace demo
    
    #endif
    

    and the cpp file

        // myobject.cpp
        #include "myobject.h"
    
        //#include "worker.h"
        namespace demo {
    
            using v8::Function;
            using v8::FunctionCallbackInfo;
            using v8::FunctionTemplate;
            using v8::Isolate;
            using v8::Local;                 
            using v8::Number;
            using v8::Object;
            using v8::Persistent;
            using v8::String;
            using v8::Value;
    
            Persistent<Function> MyObject::constructor;
    
            MyObject::MyObject(double value) : value_(value) {
            }
    
            MyObject::~MyObject() {
            }
    
            void MyObject::Init(Local<Object> exports) {
                Isolate* isolate = exports->GetIsolate();
    
                // Prepare constructor template
                Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
                tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject"));
                tpl->InstanceTemplate()->SetInternalFieldCount(1);
    
                // Prototype
                NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);
    
                constructor.Reset(isolate, tpl->GetFunction());
                exports->Set(String::NewFromUtf8(isolate, "MyObject"),
                    tpl->GetFunction());
            }
    
            void MyObject::New(const FunctionCallbackInfo<Value>& args) {
                Isolate* isolate = args.GetIsolate();
    
                if (args.IsConstructCall()) {
                    // Invoked as constructor: `new MyObject(...)`
                    double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
                    MyObject* obj = new MyObject(value);
                    obj->Wrap(args.This());
                    args.GetReturnValue().Set(args.This());
                }
                else {
                    // Invoked as plain function `MyObject(...)`, turn into construct call.
                    const int argc = 1;
                    Local<Value> argv[argc] = { args[0] };
                    Local<Function> cons = Local<Function>::New(isolate, constructor);
                    args.GetReturnValue().Set(cons->NewInstance(argc, argv));
                }
            }
    
    
            //define functions here
            void MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {
                Isolate* isolate = args.GetIsolate();
                MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder());
                double x = obj->value_;
                mycalcobj = new MyClass();
    
                x=mycalcobj->Multiply(2, x);
    
                obj->value_= x;
    
                args.GetReturnValue().Set(Number::New(isolate, obj->value_));
            }
    
        }  // namespace demo
    
  3. Create the main cpp file to initialise

        #include <node.h>
        #include "myobject.h"
    
        namespace demo {
    
            using v8::Local;
            using v8::Object;
    
            void InitAll(Local<Object> exports) {
                MyObject::Init(exports);
            }
    
            NODE_MODULE(addon, InitAll)
    
        }  // namespace demo
    
  4. The binding.gyp file is defined as:

        {
          "targets": [
            {
              "target_name": "cpphello",
              "sources": [ "cpphello.cpp", "myobject.cpp"],
              "libraries": [ "D:/East101/Adri/javascript/socketio/cpplib/build/x64/Debug/MyLib"]
            }
          ]
        }
    
  5. Build the project using node-gyp configure build

I get the following messages:

    MyLib.lib(MyClass.obj) : warning LNK4075: ignoring '/EDITANDCONTINUE' due to '/OPT:ICF' specification [D:\East101\Adri\javascript\socketio\cpplib\build\cpphello.vcxproj]


    LINK : warning LNK4098: defaultlib 'MSVCRTD' conflicts with use of other libs;use /NODEFAULTLIB:library [D:\East101\Adri\javascript\socketio\cpplib\build\cpphello.vcxproj]

    myobject.obj : error LNK2001: unresolved external symbol "public: static class MyClass * demo::MyObject::mycalcobj" (?mycalcobj@MyObject@demo@@2PEAVMyClass@@EA) [D:\East101\Adri\javascript\socketio\cpplib\build\cpphello.vcxproj] D:\East101\Adri\javascript\socketio\cpplib\build\Release\cpphello.node : fatal error LNK1120: 1 unresolved externals [D:East101\Adri\javascript\socketio\cpplib\build\cpphello.vcxproj]

I need some assistance to either fix this error and make it work as I envision it or let me know if there's a better way. I'm quite new to C++ and coding in general so I may just be approaching this wrong.

4

2 回答 2

1

你的意思是类似的吗?

How to add dependence to static library in binding.gyp?

'libraries': ['-L/path/to/dir', '-lfoo']

参考:https ://github.com/nodejs/node-gyp/issues/328

于 2021-03-03T15:55:18.027 回答
1

C++ 与 Java 等有点不同...如果你声明一个静态成员,你需要在 CPP 文件中定义它。像这样想:当你实例化一个对象时,会分配一个普通的成员变量。但是静态成员变量从一开始就存在。所以你需要在某个地方定义它来为它实际分配内存。

如果您将以下内容放入您的 cpp 文件中,则可以解决它:

namespace demo
{

    MyClass* MyObject::mycalcobj;

    //...

(例如看看这里这里

于 2015-11-09T15:14:28.440 回答