Why do we need JNI to access the native when we can develop the entire application in JAVA.
Regards,
Sujanian
JNI is needed, when you can't develop the entire application in Java. This can happen for example, when there is a legacy library only available in C or when there is a need to communicate with a system driver. If you can write the whole application in pure Java, you of course don't need JNI.
When you can develop the whole application in pure Java, you do not need JNI. That is the preferred way, too.
However:
you may want to call into existing native code libraries. It may be possible to rewrite them in Java, but that could be a lot of work (in the port and in maintaining two versions later on)
you may need to write some low-level code to talk to the hardware/OS directly in ways that the JVM does not let you
Why do we need JNI to access the native when we can develop the entire
application in JAVA.
If by this you are asserting that you can always develop the entire application in Java, you are incorrect. You can't always do that, and JNI is there to cover the gap.
If on the other hand you mean 'if' instead of 'when', the answer is that you don't need JNI in those cases.
Related
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?
What's the best way to do this....?
I have some Native C++ code that uses a lot of Win32 calls together with byte buffers (allocated using HeapAlloc). I'd like to extend the code and make a C# GUI...and maybe later use a basic Win32 GUI (for use where there is no .Net and limited MFC support).
(A) I could just re-write the code in C# and use multiple PINVOKEs....but even with the PINVOKES in a separate class, the code looks messy with all the marshaling. I'm also re-writing a lot of code.
(B) I could create a native C++ DLL and use PINVOKE to marshal in the native data structures. I'm assuming I can include the native C++ DLL/LIB in a project using C#?
(C) Create a mixed mode DLL (Native C++ class plus managed ref class). I'm assuming that this would make it easier to use the managed ref class in C#......but is this the case? Will the managed class handle all the marshaling? Can I use this mixed mode DLL on a platform with no .Net (i.e. still access the native C++ unmanaged component) or do I limit myself to .Net only platforms.
One thing that bothers me about each of these options is all the marshalling. Is it better to create a managed data structure (array, string etc.) and pass that to the native C++ class, or, the other way around?
Any ideas on what would be considered best practice...?
UPDATE:
I know I can re-write the native C++ code from scratch, but it means duplicating the code and prevents me from easily reusing any code updates with any Win32 application. What concerns me most is the best way to marshal the various data between the managed and unmanaged world. To me, a mixed mode DLL looks like the most flxible option, but I'd like to get a different perspective on the potential pitfalls.
Why not just use .NET directly? It seems to me like your problem arises from the fact that you are dependent on the original native library, but you don't mention that it can't simply be re-done in .NET.
As for .NET-native interop, PInvoke is messy, but it does work. I'd go with that if you can't change the original DLL into .NET.
Option C gives you the least work if the marshaling turns out to be simple and easy for the framework to handle (is everything blittable?). It also gives you a place to hook in your own marshaling. I wrote something about this ages ago marshaling between date types etc but I think today I would write a marshal_as<> overload between your managed and native types. It would be the most elegant solution and also the least code.
Update: found my old article - it was for PInvoke. http://codeguru.earthweb.com/columns/kate/article.php/c4867/
I have a data acquisition program written in C++ (Visual Studio 6.0). Some clients would like to control the software from their own custom software or LabView. I would like to come up with a simple API with a dll I can distribute to them and would like some tips on how to get started. This is going to be VERY basic, maybe 4 or 5 commands. My DAQ program will still be running in its own window on the same machine, I would just like to set it up to be controlled from another program.
You are on the right track with a DLL. The real trick, it sounds like, will be deciding what sort of inter-process communication (IPC) you want to use. Options are: sockets, pipes, shared memory, synchronization objects (events, etc.), files, registry, etc.
Once you decide that, then implement a listener within your executable to wait for incoming IPC messages from whatever software is using your DLL.
As far as the API is concerned, you can keep it simple just like you were wanting. Have the DLL expose your 4 or 5 functions (make sure you only use native data types, like char* and long, to avoid module boundary issues), and then those will use your IPC mechanism to communicate with your executing app.
Things that start simple like this have a habit of growing over time, so you may be better off doing a little more work up front and using a technique that will grow with you.
Implementing a COM interface to your program would give the clients are lot of freedom in how the interface with it, and you wouldn't have to worry about the mechanics of IPC, etc since COM is designed to hide all that from you.
In the future COM already has well define idioms for things like events that are well support by scripting languages, etc should you need them.
Update: there are a lot of ways of implementing COM. You can build it from the first principals with the guide of a good COM book, or use of framework like ATL to save some of the boiler plate. There are a lot of good samples, for example see MSDN.
The big advantage of COM is that you don't need a DLL! Your application would always be running, you say. That means that it can act as the COM object creator ("local server").
If someone would want a "stdcall" DLL instead, you could give them a DLL that internally just forwards all calls to the COM interface. Writing it would be quite trivial. You only have 5 functions, you say. That suggests you have one COM interface, with those 5 methods. When the wrapper DLL loads, it asks your EXE to create its COM object. The DLL in turn exposes 5 stdcall methods, each of which calls one method on the COM object.
You could use a dll. I'd consider it. But I'd also consider whipping up a simple http-based API, preferably RESTful.
Advantages: Easy to port. Can write a client app from any language trivially. Can work across a network. Testing becomes easier (use a scripting language or your browser).
Disadvantages: Performance is going to be slower. Significantly more plumbing to set it up in C++. I'm not sure if LabView can make http calls.
Something like:
http://xxx/data [GET, maybe POST for testing]
http://xxx/data/start [POST]
http://xxx/data/stop [POST]
http://xxx/data/parameters [POST]
Given your requirements it may be slightly overkill but then maybe not. Many apps I've worked on have had to be ported and would have been quicker to extend if we could have used a faster dev language to test and extend it.
LabVIEW supports making DLL calls, but this is one of the weaker spots in LabVIEW development. Done incorrectly, this can lead to an application that is more prone to crashes. As a LabVIEW developer, I like MattyT's suggestion of creating an HTTP service. Every language on every platform that can make a TCP/IP port can access it then. I think you could use your own custom TCP/IP protocol instead of full bore HTTP, but either way the compatability issue is solved.
If you do use DLLs, here are some tips. Don't use structs or pointers to structs in your function call argument list. Don't allocate memory in the DLL to be passed back to LabVIEW. LabVIEW has built in memmory management and won't play well with others. This may apply to other languages that have memory management such as Java. LabVIEW will work better if it allocates the memory and passes a pointer to the DLL. Avoid pointers, arrays and strings where possible. LabVIEW can pass these to DLLs, but it is an advanced topic and works best when the LabVIEW developer also knows C, which will not always be the case.
There is a related question here. I don't want to end up with something that is LabView-specific, and it appears that LabView can access dlls if they use stdcall. A dll like this would be callable from a VB or other Windows software as well which is what I'm shooting for.
I'm not sure about it's ability to access a COM interface but would appreciate some more detail on what that would look like for my application.
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.
I need to build a C++ library to distribute among our customers. The library must be able to be accessed from a wide range of languages including VB6, C++, VB.net and C#.
I've being using ActiveX controls (ocx files) until now. But I wonder if there is a better kind of library (dll, etc.) that I can build. What do you recommend?
I'm limited to C++ as the library language, but you can mention other languages for reference to other developers.
P.S. Sorry if the question was already asked. I had some trouble finding a suitable title. Feel free to correct my English.
Edit: Seems like the best choice is either DLLs or OCX (i.e., COM), but I'm still having some doubts on which one will I choose. Which one is more suitable to modern languages (.NET for instance)? Which one would be easier to use from an end developer perspective?
Almost every language has a way of loading dynamic libraries and accessing exported C functions from them.
There is nothing preventing you from using C++ inside the dll but for maximum portability, export only C functions.
I have some more about this in this post.
If you're looking at supporting both VB6 and .NET, you're pretty much stuck with exposing interfaces via COM, but at least that'll get you out of having to create more than one wrapper based on the language/runtime system you're trying to interact with.
If there is any chance this will need to be ported to non windows platforms then a DLL / Shared library is your best choice as a COM object really isn't at all portable.
In addition you can call a DLL from almost any platform even if it requires you to write a wrapper of some kind. It's pretty easy to wrap a dll in a com object but if you make a native com object it's a lot harder to add a C style DLL API. Plus you might want to call it from java for example and it's much easier to write a JNI wrapper to call your DLL than get it working with COM in any kind of cross platform way.
Really it depends on what platforms you really need to call it from and how certain you can be that you won't get something out of the ordinary in future.
To be callable from all those languages your only real option is going to be COM, without having to write wrappers where required (which would defeat the point)