Can we create a class in say C# which can be used in other high-level languages like Java.?
To be more specific say, I have defined a function in c#. Now can I use the same function in other languages like Java without re-writing it and by using reference or anything else to the class in c# ?
The question here is not strictly limited to any particular language? Question here is that Can we create a class in one language which can be used in other language.
Can we create a class in say C# which can be used in other high-level
languages like Java.?
NOPE.
Yes you can use such a construct. A web service is language independent or you can call(a executable programme) with a cmd command.
OP:
Can we create a class in say C# which can be used in other high-level languages like Java.?
I have defined a function in c#. Now can I use the same function in other languages like Java without re-writing it
Yes it can be done.
You can generate Java proxy classes for invoking c# by using the tool jni4net.
bridge between Java and .NET (intraprocess, fast, object oriented, open-source)
This is what they have to say on the tool:
Using reflection we grab public method signatures for core classes of .NET and Java and generated proxy classes for the other side.
We have .NET version of JNI API.
We use JNI to forward the call from .NET proxies to methods on real Java objects. (explanation)
We use JNI to register .NET implementation of native methods of Java proxies to forward call to methods on real .NET objects More...
Source and binaries are available here
But wait there's more!
Though not a requirement, you can use jni4net to call Java from .NET.
See also
How calling from Java to .NET works in jni4net
Generally spoken: No
As some answers stated: For many languages there is a way of invoking methods/functionality of compiled compiler-output, but IMO the only szenarios I can think of it beeing useful is when it comes to legacy-software or not language-independent APIs (eg. not using rest). An Example could be calling a Method of a legacy-C#-class from a Java program for the sake of downward comnpatibility or because it was meant to work with .NET only. But you must be aware that there is no general approach of doing that which would work for any language-combination and IMO this is not using a class/method, its just invoking it.
When it comes to green-field projects, I would avoid using (to many) different languages (polyglot-programming). Maintainability suffers heaviliy because Developers need to know all used languages, use different IDEs etc. Also, debugging becomes a pain.
Using the same language for different parts of a system has the huge advantage of beeing able to use classes of some kind of shared libraries which are developed/tested independently.
However: if you are forced to use different languages for some reason, I would suggest to try and recreate the required shared functionality twice for each language (it sucks I know) and pass objects around by (de-)serializing them. This way, your projects remain testable and debuggable.
Related
I have a large programme written in C++ that needs to use a specific Java library. Ideally I would like to create an equivalent C++ library that wraps this existing Java code. As such I have been looking into the JNI invocation API.
Since I am not a very experienced programmer, and I am also inexperienced with JNI and multi-language programming, I would greatly appreciate some general pointers/tips/advice as to how to tackle this problem.
Things I would be especially interested to know:
Should each Java class in the Java lib map to to an associated C++
class? I.e. in my C++ library, will I have a class each invoking a
JVM for a particular Java class? Or will I have a singular JVM through which everything is accessed? What is the best way to do this and why?
What will be the basic process and architecture for doing this?
Are there any specific resources for creating a C++ lib from Java lib using the invocation API?
Thanks a lot!
I've done this before, but it's not for the faint-hearted especially if your interface between the 2 languages is hard. Debugging can also be a pain in this situation.
To answer your points:
You should start by deciding on what functionality from the Java library you need to access in your C++ program. Is it just a few tasks? Try making a very simple interface from C++ to Java in this case. Is it complicated? Then you're gonna have to start mapping Java classes to C++, and the more you need then the more work it's gonna be.
The end of q1 is sorta q2 really. Your C++ program will start a single JVM which will run as part of your program. When you make calls across the C++ data will be transferred into the JVM, and then the Java code executed, and then the return values transferred back. This incurs a performance cost so calling small functions like add(int,int) through JNI would be more expensive than just doing it in C++.
There's a lot of basic guides you can Google to get started. Just managing to start a basic JVM from C++ and making a call is actually a bit of work since you need to get the paths to the JVM libs correct or it doesn't work (unless they've improved this, it's been years since I tried). So you might want to check that out first before asking more specific questions about JNI and mapping functions.
An alternative option (which may or may-not be possible depending on your library and use-case) is to just write some kind of wrapper service around your library, actually in Java. And then send requests to it via JSON-HTTP or some messaging system.
An even-more alternative option, rewrite whatever the library is doing in C++.
You can use scapix::link::java C++ JNI library to generate C++ headers for any Java code, then easily access this Java code from C++. Here is an example:
#include <scapix/java_api/java/lang/System.h>
#include <scapix/java_api/java/util/Locale.h>
#include <scapix/java_api/java/text/DateFormatSymbols.h>
using namespace scapix::link::java;
using namespace scapix::java_api;
void test1()
{
// C++ objects are automatically converted to and from corresponding Java types.
// This works for any type supported by scapix::link::java::convert() interface,
// which supports many STL types and can be extended for your own types.
std::string version = java::lang::System::getProperty("java.version");
std::vector<std::string> languages = java::util::Locale::getISOLanguages();
std::vector<std::vector<std::string>> zone_strings = java::text::DateFormatSymbols::getInstance()->getZoneStrings();
std::map<std::string, std::string> properties = java::lang::System::getProperties();
}
I have dll created in vb.net.
How can i use its functions in JAVA.
I found something JNI while searching on google , but not getting it.
Is there any simple documentation with example.
I would recommend Java Native Access (JNA) as its easier than using JNI. Lets say you have a DLL with some functions,
Create an java interface which has the same method signatures as the functions in DLL.
For example
public interface NativeExample{
public int method1(String param1);
public boolean mehthod2();
}
Now following is the way you load the DLL (assuming its name is NativeLib.dll)
NativeExample nativeExample= (NativeExample) Native.loadLibrary("NativeLib",
NativeExample.class);
Once you have this, you can call the method from the DLL via java methods.
`nativeExample.method("test");`
`nativeExample.method2();`
For mappings of the datatypes between Java and Native, please refer the the link above.
Here is one more example.
Exactly JNI will not give you direct access to .NET unless you work a lot on this. You can build own wrappers and use C/C++ as middle-ware but for small projects it will never pay off. Remember that calling method is one thing but passing arguments in proper types, retrieving results, subscribing events etc..etc.. is a lot more.
Therefore I would also propose to check for third-party tools which are well prepared for these kind of scenarios.
First check at least these two:
Javonet
JNBridge
Javonet I would recommend for all small and quick projects as this is light solution which provide very high performance due to in process communication and does all background work for you. All you need is call "AddReference(your.dll)" and next invoke any method using reflection-style API. You can invoke any methods, set/get fields and properties, get results, subscribe events or handle exceptions.
Very similar way works JNBridge which has a lit bit more additional staff/extensions for popular enterprise scenarios like cloud integration or websphere but this one I would recommend for bigger projects were you expect to bridge java and .net on separate machines it's more powerful but more complicated and heavy as well.
Both are free to try and Javonet is free for non-commercial and academic usage, so try, test and choose what best suits your requirements.
Well, there are third party tools / libraries that will help you connect Java to .NET. If you want to do it yourself -- meaning implement the JNI wrappers yourself -- you actually need to implement 2 sets of wrappers.
JNI will get you to C/C++, which is not allowed to directly access .NET objects. At that point, you can implement another wrapper, a .NET object with only static methods, that your C/C++ wrapper can call. Since unmanaged C/C++ code can't own .NET objects, it can only call static methods of .NET classes.
Is there any way to create native function from jni without creating dll? I mean like in python http://docs.python.org/2/extending/embedding.html
Section 5.4. Extending Embedded Python
I don't want to use dll exported functions.
Regards
You can embbed VM in a native application, call into Java from C/C++ then callback from Java back into C/C++. See the Invocation API in JNI documentation. This way there is no need for dynamic linking (DLLs). You can also dynamically generate classes in runtime by generating bytecode with native methods (e.g. with ASM) and then registering whatever C/C++ function pointers you need with RegisterNatives.
technically it is possible.
Around 6 or 8 years ago I saw a C++ implementation (it was at codeproject site presented), which created a JVM and did access Java classes. Isn't very popular, for very good reasons, are to many to enumerate here, but is possible.
I would strongly recommend to do the other side, exactly what you don't want: java invoke the dll or so, but to many reasons, but is up to you...
Perhaps JNA does what you want?
I know three is some questions about this, but I've not found the exact response.
We have a .Net dll (C#) with no dependencies or p/Invoke. So it's a full .net platform library.
One of our clientes wants to use it in a Java Application.
What's the best choice?
I've been looking at jni4net wich could be a perfect solution, but it seems don't support generics in .Net (our dll uses lot of generics dictionaries and collections)
It's JNA the best choice?
Thanks in advance
I had a similar problem several years ago. I had a dll written in Delphi. (Delphi was a Pascal-based Windows app development tool sold by Borland.) I needed to call the dll from Java, but some of the dll functionss had parameters and return types that that were incompatible with Java. (As an interesting, if irrelevant, aside, Anders Hejlsberg, who invented C# for Microsoft, also invented Delphi for Borland.) Here is how I solved the problem.
1) I did use jni to allow my Java code to call a dll.
2) I wrote a thin wrapper dll in Delphi that was the actual dll called by my Java jni code. For those functions that were completely compatible with Java, the wrapper dll simply acted as a pass though, directly calling the actual dll functions and returning the return value. For those functions that were not compatible, the wrapper dll defined corresponding methods that were compatible with Java and did the appropriate translation from Java to Delphi before calling the actual dll.
3) I also wrote a thin wrapper object above my jni calls. Again, for the most part, the java wrapper directly made jni calls for those functions that were completely compatible between Java and Delphi. However, in my case, a few functions required that I pass in Delphi objects. So, what I did was define corresponding Java objects. The main purpose of my Java wrapper object was to take these Java objects, translate them into parameters that were compatible with my Delphi wrapper dll, and then make the apprropriate jni call. Also, for those dll functions which passed back an object, my java wrapper took the java-compatible return value from the jni call, and created and asssembled the appropriate object.
This may sound like a lot of work, but it really was not (and my dll had over 100 methods, and a dozen or so Delphi object types). When I was done, writing the Java application code that actually used the dll was very straight forward.
Regarding the generics, that could be a problem. But, if in real life, the number of object types you support is relatively small (and it often is), you can just write separate calls for each object type in your wrapper. (That is what those of us who remember Java 2 used to do before they invented generics and it worked just fine, even if it was a bit less elegant.) Your application Java code could stll use generics; the wrapper would make the appropriate call based on the actual type that was passed in.
Hopefully this will give you some ideas on how you might proceed.
To use .NET DLL in JAVA I would say that the best choice is to go with native bridge like Javonet. With such bridge all you have to do is just copy .NET dll to your JAVA project folder and load it with one method call and use the .NET objects like they were JAVA objects. You skip the whole native part and get a lot of built-in tools for data types conversion, subscribing events, garbage collector, exceptions and many others.
Sample code to use "Your.dll" could look like this:
Javonet.addReference("Your.dll");
NObject yourDotNetObject = Javonet.New("MyDotNetClass");
yourDotNetObject.invoke("FooMethod", arg1, arg2);
//out of the box you get also support for all types, arrays, generics etc
yourDotNetObject.generic(Javonet.getType("String")).invoke("Foo", "sample");
//such code could call following .NET method passing String as T
//void Foo<T>(T arg);
So as you see with semi-reflection syntax you get access to whole .NET world including any custom DLL or .NET framework classes. Manual solution is good but rather for learning then using in real project as it could take more time to solve all issue then your whole project needs ;)
For more samples check this:
http://www.javonet.com/quick-start-guide/
From Clojure it is easy enough to use Java libraries...but what libraries does Clojure not have that are best done with Java?
It isn't easy to give a straightforward question to this answer, because it would be first necessary to define the difference between a Clojure library and a Java library. (Even more so, because Clojure is a Java library :))
Ok, let's start with a premise that a Clojure library is any library written in Clojure and simply ignore the Java code in Clojure implementation itself. But, what if given library uses some Java dependency, like say one of Apache Commons libraries? Would it still qualify as a Clojure and not Java library?
My own criterion (and I am guessing yours, too) for the difference between the two is whether or not the library exposes a Clojure-style interface with namespaces, functions, sequences or a Java-style interface with classes, methods and collections.
It is almost trivial to write Clojure wrappers around such Java libraries. In my experience that is very useful if you want to fit in functionality of the library in overall functional design of your application. A simple example would be if you want to map a Java method against a sequence. You can either use an ad-hoc defined anonymous function to wrap the method call, or a named function from your wrapper layer. If you do such things very often the second approach may be more suited, at least for most commonly used methods.
So, my conclusion is that any Java library should be easy to convert to a Clojure library. All that is needed is to write a wrapper for it.
Another conclusion is that it may not be needed at all. If all you want is to call the method, you may still just call the method and avoid all the architecture astronautics. :)
One potential answer may be a bytecode library like ASM http://asm.ow2.org/
But honestly, with time, any library in Java can be written in clojure. Some Java code that compiled to different bytecode can be replicated if clojure uses ASM underneath.
I strongly prefer Clojure as a language for development in general, but there are several good reasons I have found for using Java libraries or writing Java code in preference to Clojure:
Leveraging mature Java libraries - some Java libraries are truly excellent and very mature. From a pragmatic perspective, you are much better off directly using Java libraries like Netty, Swing or Joda Time rather than trying to utilise or invent some Clojure alternative. Sometimes there are Clojure wrappers for these libraries but these are mostly still in a somewhat experimental / immature state.
High performance code - I do quite a lot of data and image processing where maximum performance in essential. This rules out pretty much any approach that adds overhead (such as lazy sequences, temporary object creation) so idiomatic Clojure won't fit the bill. You could probably get there with very unidiomatic Clojure (lots of tight imperative loops and primitive array manipulation for example...) but if you're going to write this kind of code it's often actually simpler and cleaner in Java
APIs with mutable semantics - if the APIs you are relying upon depend upon mutable objects, Clojure code to interface with these APIs can become a bit ugly and unidiomatic. Sometimes writing Java in these cases is simpler.
The good news is that because the interoperability between Clojure and Java is so good, there isn't really any issue with mixing Clojure and Java code in a project. As a result, most of my projects are a mix of Clojure and Java code - I use whichever one is most appropriate for the task at hand.
Libraries for building GUIs comes to mind.
Lots of APIs. In fact, Clojure itself is built on top many sturdy Java APIs like the java.util.Collection API. And well known Clojure APIs like Incanter are built on top of libraries like Parallel Colt, and JFreeChart.
I can't find the quote at the moment; but Rich said somthing to the effect of "clojure should use java where possible" and not wrap java unnecessarily. The principal being to embrace the java platform instead of fighting it. so the general advice becomes:
If a good java library exists use it, if not write one in clojure.