How to use .Net dll in Java - java

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.

Related

How to use python in a java project [duplicate]

I have a Java app that needs to integrate with a 3rd party library. The library is written in Python, and I don't have any say over that. I'm trying to figure out the best way to integrate with it. I'm trying out JEPP (Java Embedded Python) - has anyone used that before? My other thought is to use JNI to communicate with the C bindings for Python.
Any thoughts on the best way to do this would be appreciated. Thanks.
Why not use Jython? The only downside I can immediately think of is if your library uses CPython native extensions.
EDIT: If you can use Jython now but think you may have problems with a later version of the library, I suggest you try to isolate the library from your app (e.g. some sort of adapter interface). Go with the simplest thing that works for the moment, then consider JNI/CPython/etc if and when you ever need to. There's little to be gained by going the (painful) JNI route unless you really have to.
Frankly most ways to somehow run Python directly from within JVM don't work. They are either not-quite-compatible (new release of your third party library can use python 2.6 features and will not work with Jython 2.5) or hacky (it will break with cryptic JVM stacktrace not really leading to solution).
My preferred way to integrate the two would use RPC. XML RPC is not a bad choice here, if you have moderate amounts of data. It is pretty well supported — Python has it in its standard library. Java libraries are also easy to find. Now depending on your setup either Java or Python part would be a server accepting connection from other language.
A less popular but worth considering alternative way to do RPCs is Google protobuffers, which have 2/3 of support for nice rpc. You just need to provide your transport layer. Not that much work and the convenience of writing is reasonable.
Another option is to write a C wrapper around that pieces of Python functionality that you need to expose to Java and use it via JVM native plugins. You can ease the pain by going with SWIG SWIG.
Essentially in your case it works like that:
Create a SWIG interface for all method calls from Java to C++.
Create C/C++ code that will receive your calls and internally call python interpreter with right params.
Convert response you get from python and send it via swig back to your Java code.
This solution is fairly complex, a bit of an overkill in most cases. Still it is worth doing if you (for some reason) cannot afford RPCs. RPC still would be my preferred choice, though.
Many years later, just to add an option which is more popular these days...
If you need CPython functionality, py4j is a good option. py4j has seen seen frequent updates in 2016 2017 2018 2019 2020 and has gained some popularity, because it is used e.g. by Apache Spark to achieve CPython interoperability.
The best solutions, is to use Python programs throw REST API. You define your services and call them. You perhaps need to learn some new modules. But you will be more flexible for futures changes.
Here a small list of use full modules for this purpose:
Python modules
Flask
Flask-SQLAlchemy
Flask-Restful
SQlite3
Jsonify
Java modules (for calling rest api)
Jersey or Apache CXF
You will need a small Learning curve, but later you will get more productivity and modularity and even elasticity...
My other thought is to use JNI to communicate with the C bindings for Python.
I like very much JNA:
JNA provides Java programs easy access to native shared libraries (DLLs on Windows) without writing anything but Java code—no JNI or native code is required. This functionality is comparable to Windows' Platform/Invoke and Python's ctypes. Access is dynamic at runtime without code generation.
My 0.02$ :)
You could use a messaging service like ActiveMQ. It has both Python and Java support. This way, you can leave the complicated JNI or C bindings as they are and deal solely with what I consider a simple interface. Moreover, when the library gets updated, you don't need to change much, if anything.
Have you considered running Jython on the Java VM?
I've investigated a similar setup with JNI. Maybe this will help if haven't seen it yet:
http://wiki.cacr.caltech.edu/danse/index.php/Communication_between_Java_and_Python
http://jpe.sourceforge.net/
These are some of the tools which make it easier to bridge the gap between Python and Java:
1.Jython
Python implemented in Java
2.JPype
Allows Python to run java commands
3.Jepp
Java embedded Python
4.JCC
a C++ code generator for calling Java from C++/Python
5.Javabridge
a package for running and interacting with the JVM from CPython
6.py4j
Allows Python to run java commands.
7.voc
Part of BeeWare suite. Converts python code to Java bytecode.
8.p2j
Converts Python code to Java. No longer developed.
If you can get your Python code to work in Jython, then you should be able to use that to call it from Java:
http://jython.sourceforge.net/cgi-bin/faqw.py?req=show&file=faq06.001.htp
I also think that run command line in the Java wouldn't by bad practice (stackoverflow question here).
Potentially share the data through some database.
I like the way to connect two apps via the bash pipe, but I have not practice in this, so I'm wondering how difficult is to write logic to handle this on both python/java sides.
Or other productive way could be to use the Remote Procedure Call (RPC) which supports procedural programming. Using RPC you can invokes methods in shared environments. As an example you can call a function in a remote machine from the local computer using RPC. We can define RPC as a communication type in distributed systems.
(mentioned above by Marcin)
Or, very naive way would to be to communicate by the common file. But for sake of simplicity and speed, my vote is to use the shared database x rest API x socket communication.
Also I like the XML RPC as Marcin wrote.
I would like to recommend to avoid any complication to run Python under JVM or C++ binding. Better to use today trends which are obviously web technologies.
As a shared database the MongoDB may be good solution or even better the Redis as in memory database.
Use pipes to communicate with python(a python script calls python library) via subprocesses, the whole process is like java<-> Pipes <-> py.
If JNI, you should be familiar with python's bindings(not recommended) and compiled files like *.so to work with java.
The whole process is like py -> c -> .so/.pyd -> JNI -> jar.
Here is a good practice of stdio.
https://github.com/JULIELab/java-stdio-ipc

Wrapping a Java library with C++ (JNI)

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();
}

General Programming- Cross language compatible classes

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.

Calling Java methods and classes from Perl script

I have a quite huge Java class that has several imported packages and libraries (related to natural language processing). I want to call some specific methods of my Java classes and get results back using a Perl script. How should I do this? I guess the Inline::Java is not suitable for my purpose since the Java code is quite large to be incorporated at one place.
Why is Inline::Java not suitable? You don't need to provide access to all the bits of your Java API. You can write short methods that call into your Java stuff. A small Java adapter layer can show up in your Perl code to give you the access you need. Have you tried it yet?
How big is this Java code base? I've been on projects that easily integrated big Java SDKs (although I wasn't that one doing that part).
I had ran into similar situation lately. The best solution which worked for me was to use apache thrift service and expose the required methods through it. These method were then in turn consumed by the client written in perl.

Best choice. Use .Net Dll in Java Application

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/

Categories