Can I call a c++ function from JavaScript? - javascript

There is c++ library and I need to make function calls to this library from JavaScript running on the browser on the client side, the library resides in the client machine only. How can I load the library and access the interfaces (functions) provided by the c++ library? The library contains algorithms and rendering calls mainly.

A few options I can think of:
1) Find a different library in JavaScript.
2) Port the C++ code over to JavaScript. How easy this is depends on
how complex the C++ code is or how much of it you need.
3) Wrap the C++ code in a web service on a server and call it using AJAX. I'm not personally familiar with any C++ web service frameworks, but barring that, you could create Java, Python, or .NET bindings for the library (or just for the portion that you need), or bindings in another language. Then you would write your web service in whatever language you chose.
3B) Alternative to #3 - If the library has a command-line interface, or if there exists a command-line program that uses the library, your web service could call that and you wouldn't have to write a language binding. Note however that there are performance & security problems to be aware of with this option.
4) If you have the C++ source code for the library, you could try to compile the library to JavaScript using Emscripten.
I would probably try those in that order, roughly. I might try #3 last cause it could be the trickiest.
Also, if you do #3 or #3B, you'll want to be sure your use of the library is thread-safe.
Disclaimer: I've never tried any of these except #3B.

You'd be better off creating a 'C' wrapper for the C++ library and calling that from the Javascript.
C++ is notoriously difficult to interface with due to the language standard lacking a tight ABI definition. C does not have this limitation. For this reason, 'C' ends up being the lingua franca when you want two programming languages to talk with each other.

Usually browsers doesn't allow that, because that's very insecure.
You might compile C++ in asm.js and use it as JavaScript library.
Alternatively you can create browser extension, which will run or call desired code.

Yes its possible but before you can call them from javascript. You do this by creating an interface file to tell javascript about the interface.

Related

Use methods of a java librairy .jar in node.js [duplicate]

This question already has answers here:
Call java program from Node.js application
(5 answers)
Closed 2 years ago.
I am trying to call a function defined in a java from node js .
Example :
public class A{
public void show(){
System.out.prntln("Invoked from Node JS");
}
}
and a node js file
console.log("In Node JS");
//define calling A like A a = new A();
a.show();
I may be totally wrong but I am trying to access a java function from node js .
This is a great question. In general, there are several approaches to language inter-operation:
Running code in completely separate, isolated programs / processes, and using interprocess communication (IPC) or other networking protocols (TCP or higher level protocols built on top of TCP like HTTP, often with a REST-ful API, or some form of RPC system) to send information between the two processes that have been written in different languages.
"Transpiling" one language into the other (e.g. using the JSweet or TeaVM transpilers to convert Java code to JavaScript code), and then creating a single application / process out of the original code in one language together with the transpiled code from the other language (which is now in the same language as the other code being built into that final application).
Using a common intermediate language and low-level "native" interfaces that allow the code to interoperate. Most languages have some form of interoperation with C (because C is a common denominator supported by most operating systems). While this would not work with client-side JavaScript (though some of the principles are still be relevant with Native Client (NaCL)), with NodeJs, you can call into C code using node-gyp and cwrap. Once you are in C land, you can call into Java using the Java Native Interface (JNI) (though making it possible to call your Java code from C using JNI is probably more easily accomplished by letting SWIG autogenerate much of the boilerplate for this for you, rather than directly writing to the JNI specification).
As with all things, there are tradeoffs to the various approaches:
Approach #1:
Pros:
relatively straight-forward
works with almost any programming language
each subsystem is fully isolated from the other
each system can be debugged in a language idiomatic manner
Cons:
must define shared protocol
can result in redundant, duplicated code
protocols must be kept in sync
changes must be backwards-compatible or it will break
NOTE: protocol buffers can help with this
serialization/deserialization overhead
channel can add other overhead (e.g. if communicating between processes over the Internet as opposed to on the same machine via a UNIX domain socket)
must consider security of communication mechanism
encryption of data between subsystems
access control of the endpoints
Approach #2:
Pros:
no serialization/deserialization overhead
can debug final system using idioms for target language
Cons:
not all languages can transpile from one to the other
even if a transpiler supports the two languages:
often supports only a subset of the language
may need to fix/modify code to allow it to transpile
may need to fix/modify the transpiler
slightly different semantics in transpilation can lead to subtle, surprising bugs
no isolation between the subsystems
Approach #3:
Pros:
no serialization/deserialization overhead
more support than approach #2
no need to rewrite original code in either language
Cons:
must become an expert in esoteric tools like SWIG
result is very difficult to debug
stacktraces for NodeJS code suddenly contain C, JVM, Java code
debugging tools don't easily span languages (e.g. may end up stepping through JVM code interpreting Java, rather than stepping through the actual Java code)
ownership of objects, garbage collection across languages can lead to surprising / difficult to handle bugs if ownership semantics not correctly encoded
different threading models between languages or other semantic mismatches between languages can make entire system buggy / difficult to debug
Having used systems with approach #1 and approach #3 (as well as hearing of systems using approach #2), I would strongly recommend using approach #1 wherever possible; only if you find the serialization overhead to be untenable (and you are not able to optimize the communication protocol / mechanism to handle that problem) would I venture into the other waters. That being said, approach #2 can be successful if the languages are very similar (like transpilation from TypeScript to JavaScript), and approach #3 can be successful if the use of this mechanism is very limited in scope (e.g. just need to expose one small but frequently called / performance-sensitive function this way).
I know very little about java but can't you use a node-java bridge?
https://github.com/joeferner/node-java
I think this is use node-gyp so likely works along the line of #3
If your method is public static void main, you can use node-java-caller

Relation between node.js and underscore.js

I am learning javascript and other things used with it. I have read some links that talk about nodejs and underscore.js but I don't understand how they are related. I am not sure if they are related or not in the first place. I understand that underscore.js requires node.js to be pre installed. If underscore.js is a library then what is node.js? And what is the purpose of node.js. I am sorry if this is a stupid question. I am a beginner.
They are not really related (except that both are Javascript technologies).
underscore.js is a Javascript library, like jQuery. It provides frequently used functions for use in your Javascript code.
node.js is a Javascript engine, a program that is used to run Javascript. Just like you have programs to run Perl, Ruby or Python code. In the Javascript world, this is a bit unusual, as traditionally, you would not write "server-side" programs in Javascript. Instead, the Javascript would run in a web browser, as part of a web site. The code that produces the web site on the server would be written in Java, Perl, Python, Ruby or whatever. With node.js, you can have the "whole stack" in the same language.
underscore.js does not require node.js.
In the browser, you can simply load underscore.js. If you have a server-side program, it may be running on node.js, but it could also use other engines, and underscore.js does not care.
node.js is also used as the basis for "build tools" in the Javascript world (similar to "make" for C people, or Maven for Java folks). Those are programs that a library developer uses to package the code, generate documentation, run unit tests, etc. Maybe underscore.js uses node.js to build itself.
Let's take a step back.
JavaScript is a programming language.
You probably know it's used in the browser. Node.js takes JavaScript and makes it so you can create JavaScript programs on your computer.
Now, underscore.js is a JavaScript library which provides lots of nice capabilities to JavaScript. Not necessarily on the computer/server in Node.js, but perhaps in the browser. But wherever you add it, it adds those features.
So there you have it. Both are JavaScript. There are related only by that.

Javascript C++ binding?

I have some C++ code that I want to expose to client side of a web app. Ideally, I want to write Javascript wrapper objects for my C++ classes so that I can use them clientside.
Has this been done before?. Does anyone have a link to show how this may be achieved?
There is a library to convert C++ code to javascript, it might help:
emscripten
Libjspp C++ template based wrapper for embedding and extending Javascript engine spidermonkey 1 . 8 . 5 and more
SpiderMonkey? is Mozilla Project's Javascript/ECMAScript engine.
Libjspp allows C++ developers to embed SpiderMonkey? simply and easily into their applications. Libjspp allows to run multiple Javascript Engines within same process which suits one engine per thread para dime which is helpful in achieving true parallisim. Also Libjspp no way stops user from running multiple threads within engine.
http://code.google.com/p/libjspp/
I guess that RPC is what you want. You'll need to wrap your functions on the server side using some sort of framework. I've not yet used it, but this one looks promising.
On the client side you use proxy objects to dispatch the function calls. The communication is handled usually either via XML-RPC or JSON-RPC. I used this client side framework and was quite content but I'm sure you'll find many others.
This is an old topi, however, I was in the exact situation right now, and all of the solutions I found on the net complicated or outdated.
Recently, I ran across a library which supports V8 engine (including the new isolation API, which makes 90% of the libraries I found outdated) and provides great exposure and interaction API.
https://github.com/QuartzTechnologies/v8bridge
I hope that my solution will help anybody.
There's a relatively new library for doing this called nbind. Maybe that would suit you? It looks very good to me, and I'm just about to start using it.
I think you want a C++ JSON parser. You should be able to find one here http://www.json.org/. It may not do all you want because it just serializes and deserializes C++ objects without any behavior, but it should be good enough. See https://stackoverflow.com/questions/245973/whats-the-best-c-json-parser for some discussion.
If the C++ code has to be on the client, then there is no simple way to do this for a web app. A solution may involve coding plugins for the browsers you want to support, which may then be accessed from javascript code.
If, for example, you need this for a client application, that is another case. Such a thing has been done and involves linking your application to (or running from outside) with for example chromium library, or any other javascript execution engine. That way you can create bindings to C++ classes and use such objects from javascript and vice-versa. Note that this is also not a trivial solution and may be a big effort to implement (also requires additional resources).
You could for example wrap the C++ classes in PHP or Python, and then implement an API over HTTP to access the required functions.
Or if you insist on exposing the functions as JavaScript you could try using Node.js, and create an C++ add-on to wrap you classes. See the Node.js documentation here: http://nodejs.org/api/addons.html#addons_wrapping_c_objects
But either way, I don't think avoid creating some sort of API (HTTP SOAP, XML RPC) to access the functions on your server.
Though QML is not exactly Javascript, Qt is not plain C++, but what they do together seem just like what you need

Integrating ECMA Script into a C# program, what is the fastest technique?

I'm trying to execute JavaScript in a C# program, and I'm trying to determine:
Would it be better to create a state machine for JavaScript, or should it be compiled into MSIL before executing it?
I'm really looking for techniques rather than solutions. Some attempt to compile the JavaScript, there by treating it as a programming language, others use a state machine and treat it as it was meant to be : a scripting language.
Any documentation on the methods used for executing is welcome also.
The easiest way to run JS in a C# program is to use one of the existing .Net JS runtimes: IronJS, Jurassic, and Jint. If you're interested in adding another .Net-based interpreter to the mix, examining their code is where I'd start; If you're embedding JS in your program then using a preexisting one is probably the way to go.
You haven't explained your scenario - how much javascript, how often does it get executed, how often does it change, how closely integrated it needs to be with the C# logic, and so on.
If it rarely changes, then it may be smart to compile it into MSIL via one of the alternatives.
If it changes "constantly" then it might make sense to stand up a JS compiler and send it JS as necessary. It's something like a REPL for Javascript, that you'd use programmatically. Node.js offers a server that can do REPL operations; it could listen on a port, you send it JS to evaluate, and it sends back the result. There's a free w3sockets component that could be used from cscript.exe to do something similar: for example you could build a "host" Javascript shell that listens on a socket, executes the js it receives, then sends back the result.
If it needs to be closely integrated with the C# code, then you'll have to be smarter about this. One way to do it might be to host the JS in a Windows Script Component and have the C# code invoke the JS logic via COM. You can also do the converse - have the JS host invoke the C# layer via COM to gather input and deliver results.
EDIT
A better way is to use the IActiveScript stuff - this is the official way Microsoft makes it possible to host scripting within an application. There's a winforms example published here.
OR better, see parse and execute JS by C#
Using that code I put together a demonstration of how to parse and invoke Javascript from a .NET app, using IActiveScript.
You can download a VS2010 project for this app here.

Communication between C++ and JavaScript

I need help on implementing an interprocess communication mechanism between JavaScript and C++ code. Basically I need to make a bidirectional communication. So JavaScript should be able to send and receive message from C++ (Win 32) code and vice versa.
You should look at Google's V8 JavaScript runtime, which powers their Chrome browser, it is implemented in C++. JSON libraries will simplify de/serialization.
Qt contains the QtScript module, which is a native C++ implementation of JavaScript. I've used this successfully to script a C++ application, with communication in both directions.
If you're curious, the code is part of my HP 15C simulator project.
If you have the option of using Qt, I strongly recommend it. It's comprehensive and well tested. QtScript module. QtScript is a superset of javascript. The implementation uses Webkit's javascript core.
I presume you are doing this on a Windows OS. Does any kind of IPC help or are you specific on anything? Try named pipes; or shared memory with a sync object; or try a common file system memory, such as a binary file with a sync object to access it (although this is not recommended but is sure an option).
You may also create COM objects / ActiveX controls and access this from JavaScript (browser).

Categories

Resources