how to use a SWIG generated C++ class in a java program - java

I am successfully building a shared library that is C++ and loading it in my Java program with System.loadLibrary()
My class in the C++ file was called Classifier
How do I instantiate a new "Classifier" object in java? Do I have to compile and include the java files that are generated from Swig to do such a thing? If I do not want to do that, can I just use the methods from the class?

Used correctly, SWIG will have generated a wrapper Java class called "Classifier."
Yes, this needs to be compiled -- e.g., by including it in your IDE project and/or your build.
The SWIG documentation for Java shows how to instantiate a C++ object from Java:
C++ classes are wrapped by Java classes as well. For example, if you have this class,
class List {
public:
List();
~List();
void insert(char *item);
...
you can use it in Java like this:
List l = new List();
l.insert("Ale");
...
A few other thoughts:
You can ask SWIG to place the Java class in a package of your choosing, with the -package option on the SWIG command line.
I personally keep generated code in a separate source tree. You'll be periodically deleting it, and don't want to accidentally delete non-generated code.
If you do not need access to any C++ classes in your Java code, you might find JNA easier to work with than SWIG.

Related

Generate a Java class from Clojurescript using Rhino

I'd like to do the following: I have a simple function written in Clojure/ClojureScript:
(defn add
[a b]
(+ a b))
I want to wrap this function into a Java class and put it in a jar so that I can access it in an existing Java/Android project. My previous approach was to use gen-class and create an uberjar. This however leads to some problems.
As an alternative approach I considered compiling the function using ClojureScript (a solution also suggested by Sam Beran).
So far I understand how to:
compile javascript files into Java classes
put them in a .jar
Compile ClojureScript
I'm not struggling to get the ClojureScript output into a format that can be passed on to the Rhino compiler.
Any thoughts?
IMPORTANT NOTE: I do not want to create a class with a main function as is done here!
One general way of going about this would be to:
At build time:
run the ClojureScript compiler to generate a JavaScript file
put the JavaScript file into the resource directory.
compile the Java class that uses it
make a jar file (an Uberjar or a normal Unterjar)
this Java class should:
make a java class that on initialization start up Rhino
on instantiation runs the javascript from the resource.
On a desktop of server you may not get the same awesome startup times My. Beran reported on android because processes on android have the advantage of starting life with a warmed up runtime with Rhino ready to go from the moment they start (they inherit it from the Zygote process)

Can I run a subset of pure Java code from an Android project via a regular Java main method?

I have some code in an Android project that parses HTML using Jsoup. It doesn't use anything Android specific, they're just static methods that take an InputStream, and return my model classes. The app uses Gradle to build itself in Android Studio.
Is there any way I can create a standard Java main method to do something like load HTML from a local file, run it through my parser, and output a JSON file (using Gson on my model class)? I'm thinking maybe I can add a new sourceSet to Gradle like a jvmCompatible set of classes? I would greatly prefer not to copy my code to a separate project.
EDIT:
I guess I didn't make this clear, but I would like the be able to run this locally on my dev machine from the command line, rather than on an Android device or emulator.
You don't necessarily need to do anything in the build file to set this up; the build file generates Java .class files, and you can feed them to Java directly from the command line. You can add a main method to any class:
package com.example.foo;
class MyClass {
...
public static void main(String [] args) {
...
}
}
The main method will be happily ignored util you invoke it via the Java command line. You can do this by setting your classpath to the intermediate build directory and telling the Java command line which class to start:
java -classpath app/build/intermediates/classes/debug/ com.example.foo.MyClass
where you pass in the path to the build/intermediates/classes/debug directory in your app module's build output, and the fully-qualified name of the class.
Note that if you're running a release build that uses ProGuard, this main method could get stripped out if it's not otherwise referenced in the code.
Make sure you don't access any Android classes or you'll get a runtime error.
As an aside, you might find it worthwhile to separate out your Java-only code into a Java-only module in the build. Among other things, it would let you use JUnit to write nice test cases for the classes within; if you're asking this question because you want to do some testing of your parser, you might find it convenient to do so within the auspices of a unit test.

Requiring Java Classes in LuaJ

I'm attempting to make a game library in Java that uses Lua for the scripts. The real issue appears when I try to require a Java class (that is inside of a jar), and whenever I try to do so, I get an error much like the one below:
Exception in thread "main" org.luaj.vm2.LuaError: #/C:/xampp/htdocs/LevelDesigner/Projects/Lua Test/bin/levels/Test.lua:2 module
'resources.GameLevel' not found: resources.GameLevel
no field package.preload['resources.GameLevel']
How can I require a Java class that is within a jar? Right now it seems that, with Lua, I can only require .lua files, and not .class files. This is obviously problematic as Java files are compiled down to class files...And that is what I need to require.
The answer to this question is to use luajava.bindClass as opposed to require in all of your Lua scripts.

Accessing a Python object from Java Code in Jython 2.5

I have an application using Jython 2.1.
In the app I was using jythonc to convert the python scripts to java classes and then include these classes in my webapp like any other.
So I was able to assign package name to python scripts and access these classes like any other java class.
Now I plan to migrate to Jython 2.5. Jython 2.5 has removed support for jythonc.
So I tried to use
jython -m compileall /path/to/my/python/scripts.
When I do that I get all the compiled bytecode files in the same folder. Each of the files have names like myclass$py.class (where my python file is myclass.py).
My questions -
First of all can I access these classes in another normal java
class?
If so, what is the class name I should use ? When I use it like new
myclass() my code does not compile.
Is there a way, I can assign / force a package name or class name
for the generated bytecode with compileall?
Note -
I need to upgrade to jython 2.5 because I need newer versions of
python that it supports.
I would like to stick with pre-compiling the
python code into bytecode, as I want to do optimizations on the
bytecode. So the recommended object factory method is only a
last resort. I am assuming the object factory approach will not allow
me to process the generated bytecode.
Any help is appreciated.

Loading a Windows DLL in Java and initiate a class from it

I have a Windows DLL file from .NET, namely "System.Management.dll". I work with it using the code I write below:
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_LogicalDisk WHERE Name = 'C:'");
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("Win32_LogicalDisk instance: ");
if (queryObj["VolumeSerialNumber"] != null)
{
Console.WriteLine("Drive Name : " + queryObj["Name"]);
Console.WriteLine("VolumeSerialNumber:", queryObj["VolumeSerialNumber"]);
SysdriveSerial = queryObj["VolumeSerialNumber"].ToString();
}
}
Now I need this piece of code to be in Java. So can I do this? Without anything like c++ unmanaged code. I don't want to use c++ unmanaged code to call to this dll.
I want something like this :
public class CallToCsharp {
private static native void ManagementObjectSearcher();
public static void main(String[] args) {
System.loadLibrary("System.Management");
System.out.println("Loaded");
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_LogicalDisk WHERE Name = 'C:'");
}
}
Well this last code I have to put it in Java. How can I load this DLL and call the DLL to instantiate the native class in DLL and use its methods?
Update
I saw the thing, it seems it's a lot of work to do in case I have to use that class, like selecting each of them in .net Reflector and converting them to jar files. Now as per that tutorial I saw the jar files don't contain any real code to be used.
How to use it? I mean if I need to generate the jar file actually working with the code enough. How to go about it?
And aren't there any alternatives to this?
This is not an easy road you want to go down but IKVM might be able to help.
Overview
IKVM makes it possible to develop .NET applications using the Java language. Here's how it works:
Identify .NET classes you want to use in your application.
Identify which .NET dll's contain the .NET classes you identified in step 1.
Tip: If you're developing on Windows, the Microsoft .NET SDK Class Reference documentation
identifies the assembly / dll for a .NET class at the bottom of each class overview page.
Use the ikvmstub application to generate a Java jar file for each dll you identified in step 2.
The ikvmstub tool analyzes the .NET classes in the designated dll and generates a jar file
containing Java interfaces and stub classes. This information is needed by the Java source
compiler, which knows nothing about .NET assemblies.
Compile your Java source code using javac or jikes, with the ikvmstub-generated jar files on the
compiler classpath.
Compile the resulting Java classes using ikvmc. Use the -reference option to reference the dll's
containing the .NET classes you used; do not include the ikvmstub-generated jar files on the
compiler classpath.
For an example of this, see the tutorial.

Categories