ReactNative expose C++ native module - c++

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?

Related

Can I use pure native C++ to write apps for windows 8 metro?

With native c++, I mean, not managed c++, not cli, not any special things from microsoft, I can:
1) get high performance
2) use existing c++ code library and engine
3) write cross platform code (for example, for ios and android)
it needn't be fully native c++, I can use managed code to do the ui things, like object-c in ios and java in android, but beside interface, can I use native c++ code?
I suggest you have a look at the presentation here: Using the Windows Runtime from C++ and especially at the comments from Herb Sutter. I quote:
Please answer this question: If I decide to write C++ GUI application
in Metro style am I forced to use all these proprietary ref, sealed,
^, Platform::String^ extensions for GUI components or not?
#Tomas: No, you are not forced to use them. We are providing two
supported ways:
1) These language extensions (C++/CX).
2) A C++ template library (WRL), see
Windows Kits\8.0\Include\winrt\wrl as Yannick mentioned. WRL is a C++
library-based solution sort of along the lines of ATL, which offers
what I think you're looking for -- template wrapper/convenience
classes and explicit smart pointers and such.
Yes you absolutely can, real native C++ is fully supported.
You do however mostly have to use the new WinRT libraries to do an user interface or system calls and although they are native code and fully callable from C++ directly the interface to them makes it very painful indeed to do so, as everything is a reference counted COM object and in addition it's not so easy to create instances of them as just calling "new" so you have to write a lot of ugly code to do so.
As the earlier answer said, microsoft provide two ways to help with this. One is via language extensions to c++ and the other is a c++ template library. Personally I consider both to be rather ugly for doing something as simple as calling an API but that's just me :)
But to answer your question, it's completely possible to write your application in real native c++. You won't need to use managed code at all for anything. But you'll probably want to use either the language extensions or the template library to make calling the API more easy.
Personally I'm hoping someone writes a wrapper for WinRT that exposes the most necessary functionality as a more usable c++ native library and then everyone can just use that from c++ instead...

Wanted: Compiler Tool for Users of Software System

I am not sure if the title of this question gets to the point. I have written a large software system in C C++ for Windows, and want to give the users of this system the option to add compiled code to it. The user should be able to do basic stuff, and exchange data with my program.
Currently the implemented way is via DLLs. But for this, a grown up compiler is needed, and it is not as easy as I wished. Is there a tiny C compiler that can create Windows DLLs?
Another idea is the Java native interface. But this requires a complete Java system to run in the background, and it is not easy to run code in it.
Do you have any other ideas?
Any interpreted language? (TCL and Lua were designed as extension languages, but you can nearly as easily interface with any other).
How about python integration?
You could create an python interface that interfaces with your application. Python is rather easy to learn and should integrate easily with c/c++. The python documentation has an own chapter on that.
You could also use a tool like swig to generate the interface.
The advantage of this is that they wouldn't have to compile anything. They could just supply python files that could be loaded into your application and run within the software. This is a well known use for python, and something its simple syntax promotes.
As the other says you will be best of by providing an embedded language.
I would chip in for javascript and use the google v8 engine
By using javascript you get a language nearly everbody can use and program in.
There is other javascript engines you can embed like SpiderMonkey.
See this answer for what to choose.
An interpreted language is not good enough. I need speed. The software itself is an interpreted language. So I added support for the tiny C compiler. It is only C, and I do check mingw, which probably would not be as tiny as this. Thanks for all your hints.
Added after several months:
I have now two tools, actually: TinyC and Python. The speed difference between those is noticable (factor 5-10), but that usually does not matter too much. Python is much easier for the user, though I managed to integrate both into the Euler GUI quite nicely.
One of the ways is to add scripting. You application can host scripting environment and expose its services there. Users would be able to execute JScript/VBScript scripts and interact with your application. The advantage is that with reasonable effort you can get the power of well known and well documented scripting languages into your application (I suppose there is even debugger for scripting there). You will be required to shape your app services as COM interfaces and scripts will be able to access them automatically using method names you assigned on C++ side.
C++, Win32 and Scripting: Quick way to add Scripting support to your applications
MSDN Entry Point - IActiveScript interface

what's the best way to write a pluginable application?

I want to write a native application that can be extended with plugins, perferabily in the form of dynamic libraries. I have an idea of what to do, but I would like some ideas, especially best practice tips on what to do and not to do. I worked with similar things on java and php, so I hope I don't bring any bad habits in to my C++.
I'm thinking of allowing developers to implement certain functions like "on_recieve_data(App* app, void* data)" and my application will load all the plugins and call their on_recieve_data function with a pointer to itself (dlsym?).
There are a few things that I consider very important for plugins:
Language support
If you want to reach the most number of platforms/languages/compilers then you should write the plugin interface in C and not in C++. The plugin developers can still write their functions in C++, of course, it is just the interface that is C. The problem is that each C++ compiler mangles symbol names in its own way, so if you use C++ you will be forcing plugin developers to use the same compilers and tools that you use. On the other side, there is only one way to export C symbols, so using a C interface for the plugin will allow developers to pick whatever tools they like, and as long as they can produce standard .so/.dll libraries they'll be fine.
Memory allocation
In some platforms there are problems when memory allocated by the application is released by a DLL or viceversa. If the plugin has functions that are supposed to allocate memory, then make sure you also require the plugin to provide a corresponding function to release that memory. Likewise, if the plugin can call a function in the application to allocate memory, you should also expose a release function for that memory.
Versioning
It is likely that you will have to revise the plugin API after plugins have been written. So your application needs to be prepared to load plugins developed for an older version. You should require an 'init' function in the plugin that the application calls to determine what version of the API the plugin implements and any other information the app might need to know, like the plugin type (if there are different types), what is implemented and what isn't, etc.
Also you have to be very careful when you have to revise the plugin API. You can't change existing functions, since that would break older plugins. Instead you will need to add alternative versions of those functions that have the improvements. Then the problem comes of how to name the new version of an existing function. Typically they'll get the same name plus some suffix ('Ex', a number, etc.). I haven't seen this problem solved in a way that I like.
Likewise, you have to take precautions for structures that are passed between the application and plugins. A common approach is to make the first member of all structures the size of the structure. This works as sort of a versioning mechanism, so that the application can determine what the structure looks like from its size.
Here are a few links that might be of interest:
C-Pluff, a general purpose plug-in framework in C (MIT license)
lighttpd's plugin.h header file
This page has a discussion on how to implement a plugin architecture under Mac OS X, including a short overview of a how to create a C interface for plugins.
Blender is an interesting one. The application is written in C++, but plugins are written in Python. Not a bad idea really, it makes it a lot easier for developer to write plugins.
There are plenty of applications written in scripting languages that support plugins (Wordpress, Drupal, Django, and many more). You can look at any of those that are closer to the kind of application you are writing for ideas.
I believe that this post -> Design Pattern for implementing plugins in your application? does answer your question I guess. It has a lot of refernce for plugin model.
Perhapse, the Eclipse architecture can serve as example:
http://www.eclipse.org/articles/Article-Plug-in-architecture/plugin_architecture.html
I'm pretty there is a book from Eclipse's creator, but I can't remember neither the author nor the name of the book.

Implementing A Plugin System in C or C++ [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
What are your tips on implementing a plugin style system?
In C (and I think C++ too although I haven't done it myself), this is most typically done using dynamically loaded modules. The API:s for such are platform-dependent.
On POSIX (Linux), you use the dlopen() family of functions. Basically you build your plugin separately, then load it at run-time, look up its symbols by name, and can then call them.
For Win32, there is LoadLibrary() which does something very similar, you build your code into a DLL.
For a handy wrapper that makes all of these easy and transparent, check out GLib's GModule API.
In the '92/'93 time frame I worked on a plugin architecture for Aldus PageMaker, which was coded in C++. PageMaker was built on a C++ OOP framework called VAMP, which assisted its portability between Mac OS and Windows.
So we tried to use the features of C++ to build a plugin architecture. This proved to be very problematic for C++ classes due to the so-called brittle base class problem. I proceeded to write a paper that was published in journals and that I presented at OOPSLA '93 in a reflection workshop. I also made contact with Bjarne Stroustrup at a Usenix conference in Portland and proceeded to dialog with him for several months, where he championed the issue of dealing with the brittle base class problem on my behalf. (Alas, other issues were deemed more important at that time.)
Microsoft introduced the COM/DCOM system and for that platform that was looked on as a viable solution to the problem. C++ could be used as an implementation language for COM via abstract classes used to define COM interfaces.
However, these days developers shun away from COM/DCOM.
In contrast, NeXT devised a plugin architecture using Objective C in the early 90s in the NeXT Step framework. Today that lives on vibrantly in Mac OS X on Apple's computers and important platforms such as the iPhone.
I submit Objective C enabled solving the plugin problem in a superior manner.
I personally regard the brittle base class problem of C++ to be it's most fatal flaw.
If were building a plugin architecture with the C-based family of languages, would do so using Objective C.
The best platform and language neutral advice I can give is this:
Design your entire app around the plugin SDK.
IMO, a plugin SDK should not be an afterthought. If you design your app to basically be an empty shell which loads plugins, then the core features are implemented in your own SDK, you get the following benefits:
High modularity of components, and clear separation of purpose (it kind of forces your architecture to be good)
It forces your SDK to be really good
It allows other third party developers to make extremely powerful, core-level features as well
New developers/hires can easily start work on a major new feature without having to touch the main app - they can do all their work in a plugin (which prevents them screwing up anything else)
In C/C++, you probably use dynamic link libraries and either function pointers (C) or interfaces (classes solely consisting of pure virtual methods, for C++). However even if you use Javascript, I'd still recommend the above architecture.
Qt provides QPluginLoader:
http://qt-project.org/doc/qt-4.8/qpluginloader.html
If you need/want more fine grained control, Qt also provides a means to load libraries on the fly with QLibrary:
http://qt-project.org/doc/qt-4.8/qlibrary.html
Even better, these are portable across platforms.
This may not be what you're looking for, but you could embed a scripting language in your application, such as Lua. Lua was designed to be embedded in other programs and used as a scripting language for writing plugins. I believe it's fairly easy to add the Lua interpreter to your program, though I don't know Lua so I can't vouch for how effective of a solution this would be. Others with more experience with Lua, please add comments about your experience with embedding Lua in another application.
This would, of course, mean that your plugins need to be written in Lua. If you don't like Lua then the de-facto standard Perl, Python and Ruby interpreters are all written in C, and can be embedded in a C program. I know of a number of programs that use these languages as scripting language extensions.
However, I don't know what you're looking for, as your question is a little vague. Perhaps more information about what you want people to be able to do with said plugins would be appropriate. For some tasks, a full-blown scripting language may be a bit overkill.
I have written an article about how to implement a plugin system using Dynamic Linking Libraries. The article is written from the point-of-view of a Windows programmer but the technique can be applied to a Linux/Unix type environment.
The article can be found here: http://3dgep.com/?p=1759
The main point is, you should create a "common" DLL that is implicitly linked by both the main application (the core application) and by the plugin implementations. The plugins can then be explicitly linked and loaded dynamically at run-time by the core application.
The article also shows how you can safely share static (singleton) instance of a class across multiple DLLs by using the "common" DLL.
The article also shows how you can export a "C" function or variables from a DLL and use the exported functions in the application at run-time.
It's best to use a framework like ACE (http://www.cs.wustl.edu/~schmidt/ACE.html) that shields you (as good as possible) from platform specific coding.
ACE contains a plugin framework that is based on shared libraries that you can use to create dynamically assembled applications.
For a higher level abstraction check out CIAO (http://www.cs.wustl.edu/~schmidt/CIAO.html) the Open Source C++ implementation of the CORBA Component Model.
Look at Poco Class Loader, it can be interesting for you.
I have written a plugin library Pugg that loads C++ classes from dll files and here is the logic I used:
User exports a c function from dll that has a unique name. This name has to be unique enough as functions cannot be distinguished using their arguments while loading from dlls.
C function registers one or several factory classes called "Driver". Every Driver class is associated with a string. When the main application wants to create a class, it gathers the related factory class using the associated string. I also implemented a version checking system to not load old plugins.
Dll loading is accomplished using the LoadLibraryA and GetProcAddress functions (Pugg currently works on windows).
One thing worth mentioning is that main application and dlls should be compiled using the same compiler and using the same compilation options (release/debug modes, optimization settings, stl versions etc...). Otherwise there might be issues with mapping of classes.
I have had some success using a fairly naive system:
Create API Specification for plug-ins
Use a singleton plug-in manager
Use LoadLibrary/GetProcAddress based run time dynamic linking
Implement Inversion of control based event handling for notifying the plug-ins
This podcast on plugin architectures might also be interesting.

Options for refactoring bits of code away from native C++?

So, one commonly heard comment when talking about performance is that you write your code with whatever language gets the job done fastest. If performance in specific areas is a problem, then rewrite those bits in C/C++.
But, what if you're starting with a native C++ app? What options do you have if you want to write the easy bits, or refactor the old bits, in a language like Python, Ruby, C#, or whatever? Keep in mind that transferring data between the native and other sides is a must. Being able to simply call a function written in an "easier" language, while passing C++ classes as data, would be beautiful.
We've got a crusty Win32 app that would benefit greatly if we could crank out new code, or refactor old code, in C# or something. Very little of it requires the complexity of C++, and dealing with the little fiddly bits is dragging down the programming process.
As Aaron Fischer suggests, try recompiling your C++ application with the /clr option turned on and then start leveraging the .Net platform.
CLI/C++ is pretty easy to pick up if you know C# and C++ already and it provides the bridge between the .Net world and native C++.
If your current C++ code can't compile cleanly with /clr turned on then I'd suggest trying to build your application as a static lib (without /clr enabled) and then have your main() be in a CLI/C++ project that calls your legacy app entry point. That way you can at least start leveraging .Net for new functionality.
For examples of "legacy" C/C++ apps that have been "ported" to .Net CLI/C++ check out the .Net ports of Quake 2 and Quake 3: Arena.
Well, it really depends on the language. Python interfacing, for instance, is most easily done with Boost Python, and many other languages will require you to interface them as you would with C, using their C library and declaring your callbacks to be extern "C" (unfortunate that you can't use the C++ class definitions in other languages usually).
But I would also ask what you intend to use it for as C++ is a complex language, but once you get familiar with it, it is very powerful and not very much harder to code than other languages. The only really good exception I could think of is if you plan on using a powerful library that exists only in one language and there isn't a decent C++ alternative (graphics libraries are probably the best example of this because you have to be very familiar with them to use them effectively).
It's also worth pointing out that if you interface C++ code to another language, you lose out on the inter-platform compatibility granted by that language.
If you want to work between C++ and Python, than Boost Python is what you're looking for. You can write C Python bindings by hand for Cython, but that limits in many ways how you're going to write your code. This is the easiest way, as seen in some snippets from this tutorial:
A simple function that performs a hello world:
char const* greet()
{
return "hello, world";
}
The Boost python code needed to expose it to python:
#include <boost/python.hpp>
BOOST_PYTHON_MODULE(hello_ext)
{
using namespace boost::python;
def("greet", greet);
}
How to use this code from python:
>>> import hello_ext
>>> print hello.greet()
hello, world
Going in the opposite direction is bit tougher, since python doesn't compile to native code. You have to embed the python interpreter into your C++ application, but the work necessary to do that is documented here. This is an example of calling the python interpreter and extracting the result (the python interpreter defines the object class for use in C++):
object result = eval("5 ** 2");
int five_squared = extract<int>(result);
You can change the common Language run time support in your c++ project to /clr. From this point you can use any .net functionality right in your c++ code. This includes creating winforms in your project as well. You can also add a c# library that handles ui and other functionality.
In the .NET world you always have the option of crreating a COM/ActiveX interop layer for your C#/VB.NET assembly.
You can then use the normal COM API from your C++ application to create an instance of this COM server that actually wraps your .NET assembly.
Good thing about this is that simple parameters such as int, bool, string, float etc are mapped to their COM equivalent for you. However to my knowledge it is not possible to easily pass full .NET objects (instances of classes you create).
Also be aware that COM interop calls are relatively slow. You should not be calling a COM interop method continually from your C++ code in a tight loop.
COM/ActiveX have traditionally relied on the Windows Registry, not ideal as it is a big dependency. However it is also possible to to use Registration-Free COM interop to avoid this dependency.
This article covers the steps required to register a .NET assembly for COM interop.