How does a language "binding" communicate with the existing library? - c++

Im trying to understand how a binding (port) to another language works in general, but to help clarify my question I will use the direct example of a project called libsass (A C/C++ implementation of a Sass compiler).
There is another project node-sass
which is Node.js bindings to libsass.
Im assuming this means node-sass is a javascript program which runs on nodejs and nodejs acts as a proxy forwarding instructions to the libsass C++ system level program.
My question is: how does the nodejs intepreter "talk" to the libsass C++ application? - is it using sockets?
sub question: If node-sass exposed an API in the node environment by initialising objects, functions etc that were available to your own node scripts - is this by definition -the "binding"?

The C++ library part is, given that it´s really a library and not some server program, not running by itself and not listening to some socket. If a C++ lib is used in a C++ program, it´s integrated in this programs process too and not running somewhere else.
Many languages have built-in possibilites to access native C language APIs, including Node.js (with C being the de-facto standard for language interoperabilty, eg. because every somewhat important OS consists mainly of C too.). About C++ vs C, it´s not hard to write something in C++ and provide a C interface too.
In such cases, a language binding often is nothing more than something to wrap the complicated native access part in something more easy to use in the target language.
To elaborate a bit further because of the comment:
The OS itself has functions (to be used in C programs) to load C libraries on the fly, get specific functions of them and call them, without the names of lib and functions being known when the C program is compiled (eg. you could make a C program which asks the user to enter a lib name which is then used...).
Independent of that, every language is either made in a way that programs are compiled to "real" programs containing CPU instructions etc., these programs can be executed directly (example: C), or the programs of the language are made is some other format, but a "real" program is needed for every start to help the OS/CPU understanding what should be done (example: Javascript, Java.... You can´t run a program alone without having helper software installed, like a browser or the JRE).
For this second type, the helper software can make use of the lib loading functions of the OS, and if the JS/Java program contains instructions to do so... (and for the first "real" type, a certain level of compatibilty with C libs is automatically given because they use the same binary format (yes, that´s simplified))

Related

How does the C++ standard library work behind the scenes?

This question has been bothering me so much for the past couple of days. I was wondering how the standard library works, in terms of functionality. I couldn't find an answer anywhere, even by checking the source code provided by the LLVM compiler which is, for a beginner like me, a really complicated piece of code.
What I'm basically trying to understand here is how does the C++ standard library work. For example let's take the fstream header file which consist of a bunch of functions that help to write to and read from files.
How does it work? Does it use the OS specific API (since the library is cross platform), or what? And, if the standard library can do it, aren't I supposed to be able to mess with some files as well without calling the standard fstream file (which to my experience I can't do)?
I apologize if my questions are unclear since I'm not a native English speaker: feel free to modify this text so as to make it clearer.
Does it use the OS specific API (since the library is cross platform), or what?
At some point, the OS specific API is used. The fstream implementation does not necessarily call an OS function directly. It might use other classes, which call functions inherited from C, etc., but eventually the call chain will lead to an OS call. (Yes, the details are often too complicated for an intermediate programmer to follow. So, as a self-described beginner, your findings are not surprising.)
The library is cross-platform in the sense that on your end (the C++ programmer), the interface is the same regardless of platform. It is not, however, the same library on every platform. Each platform has its own library, exposing the same interface on the C++ side, but making use of different OS calls. (In fact, the same platform might have multiple standard libraries, as the library implementation is provided by your toolchain, not by the standards committee.)
And, if the standard library can do it, aren't I supposed to be able to mess with some files as well without calling the standard fstream file (which to my experience I can't do)?
Yes, you are allowed to. Apparently, you have not been able to yet, but with some practice and guidance you should be able to. Everything in the standard library can be recreated in your own code. The point of the standard library (and most libraries, for that matter) is to save you time, not to enable something that was otherwise unavailable. For example, you don't have to implement a file stream for every program you write; it's in the standard library so you can focus on more interesting aspects of your project.
A compiler is just a program which create executable file or library. You can use the compiler default libraries to gain time or write your own. The default libraries communicate with the os for file operation or memory allocation and provide a simple standard classes to allow the developper to write only one code which work on all target platforms supported by the compiler and the libraries. If you want to write your own you have to write each function for all your target os.
The standard library is cross-platform in a sense that its interface does not change between platforms but its implementation does - or in practical terms - if you only use C++ and its standard library, you can write your code the same way for Linux / Windows / MacOS / Android / Whatever and if you find a C++ compiler for one of those platforms that supports the language features you used, you will be able to compile your code for that platform without rewriting anything.
So while you can use std::vector or std::fstream or any other feature in the library independently of the platform you're writing for and expect the function definitions, type names, etc. to look the same, you cannot expect the executable which you compiled for PC with Windows 10 to run on a phone with Android. You cannot even expect the same executable to run on the same PC but with different system - that is what I mean by "the implementation is different"
There are two main reasons for this difference:
Processors with different architectures (x86-64 and ARM for example) use different instruction sets and as such the C++ source would need to be compiled to a completely different machine code to run properly
Computers with processors of the same architecture which have a different operating system have different ways of dynamically allocating memory, creating files, creating streams, writing to console, creating and scheduling threads etc. - which is part of the system functionality that you use via the standard library
If you really wanted to you could use HeapAlloc() instead of operator new() or CreateThread() instead of stdlib's std::thread but that would force you to both rewrite your program every time you wanted to compile it for something else than Windows and recompile it with the target platform's compiler (and by proxy learn its API). Standard library saves you from that trouble by abstracting away those system calls.
As for the fstream in particular, here is what it uses internally on most PCs nowadays.
Basically, fstream, iostream and printf works based on a kernel function write(). When your code call printf (we use printf as an example), it will finally call write() to let the kernel work on the IO stuff. After that, write() returns and printf returns and your code continues.
So if you really want to know how the printf works internally, you have to read the source code of the Kernel.
But you shouldn't do that for now.
For a beginner, do not try to go deeper when you haven't got a basic cognition about computer. A computer is a project, just like a building. So the right way to learn it is to learn it level by level. First, learning how to use brick and cement to build a building, this is what you should do for now. What you shouldn't do is that you are learning how to build a building and this is your first time to try to use brick, then you are interested in how to produce a brick and start to focus on brick, this is a wrong way to learn IT.
If you are learning C/C++, just learn it. Remember, learn it level by level. For now, knowing how to use printf is enough.

Use C++ library object from within Lua

So for the past few hours I've been trying to figure out how to use C++ classes contained in static (or dynamic) libraries from within Lua. I've found several packages, such as LunaFive or SimpleCppBinding, but I seem not to understand how to use them properly. From what I see there's a main function, therefore I guess it's not a library, but an executable which I run and then run the Lua script, which will hook the app and get the class, or something? What I basically want to do is:
create a library containing, for example, a class 'Player' in C++
modify this library to be usable from Lua
somehow use this class and it's methods from within the Lua in the same way as if it would be a Lua class
Is such thing even possible? And if so, could someone explain how such thing can be done?
I'm currently on Windows, but I can do it on Linux as well. On windows I'm using VS, on Linux I'd be using CLion paired with g++. Lua 5.3.
I'm not sure if this is somewhat relevant, but I'm developing a game-mode for FiveM (GTA V multiplayer client). The FiveM comes with a Lua support for scripting by default, but I'd love to use some of the C++ standard libraries and features. Therefore I'd really love to create some libraries for the server in C++, and then use them from within the Lua supplied by FiveM.
Static library: not possible. Your options are: 1. a dynamic library (binary) with some kind of interface accessible by Lua executable (Alien, Lua-specific hooks....) or 2. A custom executable which includes the Lua engine and the C++ stuff with some glue. Your examples with the 'main' function probably are the latter type.
Lua was designed, from the beginning, to be integrated with software written in C and other conventional languages. This duality of languages brings many benefits. Lua is a tiny and simple language, partly because it does not try to do what C is already good for, such as sheer performance, low-level operations, or interface with third-party software.
-Preface
I understand your pain, however Lua simply isn't meant to be used the way you intend, it's actually built to be used the other way around.
The closest thing I can think of to get the result what you want is to have a host C++ application from which you immediately create a lua state and push results of the functions you called from the C++ program into the stack, in return can be used in your Lua script and processed.
If this is something you might be able to adjust to, here is a great starting point

ReactNative expose C++ native module

We have a lot of business logic written in cross-platform C++. We want to write cross-platform UI for our application and use this business logic to create whole cross-platfrom application.
Is it possible to expose native module purely written in C++ to react-native?
We don't want to create wrappers around C++ code in native language (Java or Objective-C). Such wrappers will add more complexity it will make debugging and investigation much harder.
I am also looking for a way to do this directly in C++ without writing JNI for Android and Obj-C for iOS. I have found the CxxNativeModule class in the react native source. See the sample implementation SampleCxxModule.
The last thing to figure out is how to register that module in C++. In the JNI for React Native Android, implementation of NativeModule says
NativeModules whose implementation is written in C++ must not provide
any Java code (so they can be reused on other platforms), and instead
should register themselves using CxxModuleWrapper.
Then implementation of CxxModuleWrapper says
This does nothing interesting, except avoid breaking existing code.
So, this may help you get started. The last thing to figure out is how to register a CxxNativeModule so that it can be used in JS.
It seems as though you would need to find the code which is os dependent and write different versions of this code for different operating systems.
Here is a link which suggests how this might be done:
How do I check OS with a preprocessor directive?

CLIPS and integration with C++

I am in the process of developing a fairly complex rules engine. So I decided to take help of any GNU rules engine and get it integrated with my application. I came across CLIPS as a good rules engine.
Now, My application is in C++ and I want a sample way (a Hello world kind of program) from which I can learn how to integrate the .clp rules engine to my C++ application.
Question
My application is developed on Linux/AIX/HP and Mingw (for windows). Can we develop rules engine in CLIPS and get it integrated to C++ application on all these platforms? Can you please share a link on how to integrate.
The fundamental reason for going into an rules engine is that, I have experienced that rules "built" within my C/C++ application takes huge memory/CPU. I am under the impression that by using a rules engine, I can achieve the same in a more optimized (better resource utilization) way. Can CLIPS help me achieve that?
Update 1:
What kind of application are you developing?
To put it in a line,I am developing a filter match based counter. User may increment (NetworkID=XYZ, Increment count = 7), (NetworkID = MNO, Increment count=934)... etc. Now you get a query for NetworkID=X*, then I need to provide all count from XAA...XZZ. It is updated in multiple process, multiple thread across different node (distributed environment).
Why do you have expert system rules inside, and what kind of rules?
Now, My platform/application is in C++ (where user does increment/decrement/query). Now I want to use a rules engine to aid me in these. Writing the logic in C/C++ code seems to kill more resource that needed.
PS: The critical code related to increment/decrement/query are all in optimized c code. Some wrappers are in C++ code. So I am checking for rules engine to do it for me which can be invoked from my platform/application (in C/C++ code).
The easiest way to integrate CLIPS with C++ is to use the compiler option (if available) to compile the C code as C++ code. From Section 1.2, C++ Compatibility, of the Advanced Programming Guide (http://clipsrules.sourceforge.net/documentation/v624/apg.htm):
The CLIPS source code can now be compiled using either an ANSI C or
C++ compiler. Minimally, non-ANSI C compilers must support full ANSI
style function prototypes and the void data type in order to compile
CLIPS. If you want to make CLIPS API calls from a C++ program, it is
usually easier to do the integration by compiling the CLIPS source
files as C++ files. This removes the need to make an extern "C"
declaration in your C++ program for the CLIPS APIs. Some programming
environments allow you to specify the whether a file should be
compiled as C or C++ code based on the file extension. Other
environments allow you to explicitly specify which compiler to use
regardless of the extension (e.g. in gcc the option “-x c++” will
compile .c files as C++ files). In some environments, the same
compiler is used to compile both C and C++ programs and the compiler
uses the file extension to determine whether the file should be
compiled as a C or C++ program. In this situation, changing the .c
extension of the CLIPS source files to .cpp usually allows the source
to be compiled as a C++ program.
Optionally you can try using something like clipsmm (http://sourceforge.net/projects/clipsmm/) which is a C++ interface to the CLIPS library.

Simplest way to write cross-platform application with Python plugin extensibility?

I am writing an application which should be able to run on Linux, Mac OS X, Windows and BSD (not necessarily as a single executable, so it doesn't have to be Java) and be extensible using simple plugins.
The way I want my plugins to be implemented is as a simple Python program which must implement a certain function and simply return a dictionary to the main program.
Plugin installation should just be a matter of copying the plugin script file into the ./plugins directory relative to the main executable.
The main program should be a stand-alone executable with shared code amongst all of the above platforms, but with platform specific front-ends (so the Linux and BSD versions would just be CLI tools, the Windows version have C++ and MFC front-end, and the Mac OS X version would have a Objecive-C and Cocoa front-end).
So I guess it's really two questions:
What's the simplest way to share common controller code between multiple front ends from:
a. Objective-C on a Mac?
b. C++ on Windows?
c. C/Python from Linux/BSD?
What's the simplest way to implement plugins from my common controller to execute custom plugins?
I am with fontanini here; use shared libraries (DLLs) for the controller logic. Preferably, use C/C++ for that, and be careful with RTTI (needed for dynamic_cast<> and exception handling), which may not work across DLL borders (e.g. you might have problems catching exceptions thrown in one DLL from another one).
Look for good cross-platform libraries like Qt, which offer a lot of functionality (e.g. filesystem, processes, networking – not just GUIs, which you want to develop separately anyhow) in a platform-agnostic way.
The Python/C API is the basis for making C/C++ functionality available to Python (and vice versa), and there is only little difference between extension modules and programs that offer their own functionality to an embedded Python interpreter.
However, you might want to use a wrapper generator (all of which are based on the Python API, but require less code than using it directly) that makes your life easier. Examples are:
boost::python (which is very convenient and powerful, but has an incomprehensible hardcore-C++ implementation ;-), and leads to larger object code due to excessive template usage), possibly using pyplusplus to generate the boost::python wrapper code directly from your header files (not sacrificing the possibility to tweak the result, e.g. excluding or modifying function signatures)
SIP (in particular in conjunction with [Py]Qt, for which it was developed)
Swig (which is suitable for multiple scripting languages, but leads to APIs that rather mirror the C APIs being wrapped instead of being "pythonic")
PyBindGen which is based on the same GCCXML backend as pyplusplus, but generates pure Python/C API code directly, leading to leaner bindings (but may not grok all code out of the box)
The simplest way to share the cross-platform Python component of your application would probably be to implement it as a command-line program, and then invoke it using the relevant system calls in each of the front-ends. It's not the most robust way, but it could be sufficient.
If you want plugins to just be a file containing Python code, I would recommend that they at least conform to a convention, e.g. by extending a class, and then have your code load them into the Python runtime using "import plugin_name". This would be better than having the plugins exist as separate programs because you would be able to access the output as Python types, rather than needing to parse text from standard input.