1

I want to use a C++ library in multiple instances in nodeJs. I am using bindings npm module to wrap the C++ code. But in the end, the C++ library becomes shared object. Please help me with this

I have used the require('bindings')('library_name') with new keyword

I have cleared require cache before requiring the next instance I have used npm modules which clears cache

for (var i = 0; i < config.data.length; i++) {
        libraryObj[data[i]] = new require('library-name'); // c++ library wrapper
}

Whatever i do, the C++ library gets shared always, which is not the expected behavior.

1
  • 2
    This sounds like an XY problem. Are you trying to load multiple instances of the same library because the library has global state that you need to keep per instance? You may need to rearchitect the library then.
    – Botje
    Oct 7, 2019 at 8:25

1 Answer 1

2

I advise you to re-architect the C++ addon in such a way that you don't get this requirement.

You can't load the same module again from the same process, If you do, it returns the same handle (reference)

You can load from other processes

On Windows

The system maintains a per-process reference count on all loaded modules. Calling LoadLibrary increments the reference count. Calling the FreeLibrary or FreeLibraryAndExitThread function decrements the reference count. The system unloads a module when its reference count reaches zero or when the process terminates (regardless of the reference count).

https://stackoverflow.com/a/9190995/12167785

On Linux

If the same library is loaded again with dlopen(), the same file handle is returned. The dl library maintains reference counts for library handles, so a dynamic library is not deallocated until dlclose() has been called on it as many times as dlopen() has succeeded on it. The _init() routine, if present, is only called once. But a subsequent call with RTLD_NOW may force symbol resolution for a library earlier loaded with RTLD_LAZY.

https://stackoverflow.com/a/9191147/12167785

1
  • Later on I found that only the latest node worker supports this feature. I have re architect-ed the current library for my need. Nov 6, 2019 at 5:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.