How to declare and call a native method containing pointers in java - java

How to declare and call a native method in c containing pointers using java?
please it is urgent.Because there is no concept of pointers in java i am getting error.

Use JNI(Java Native Interfaces) to call native methods in java. Use this JNI specification pdf as a reference "java.sun.com/docs/books/jni/download/jni.pdf".

There is even a easier approach to the subject, if you or your boss are willing to pay 50$!
Is called eXcelsior xFunction. Try the evaluation version.
Works very well and is simple to use.
The only thing xFunction library does not do have is implementation of address arithmetic in Java, which i assume you will possibly never need.
From their site:
With xFunction, you no longer need to implement those ugly native methods. Instead, you extend and instantiate xFunction classes to create conventional Java objects representing external functions, data structures, pointers, and callbacks. All necessary data conversions and external function calls are done seamlessly by the xFunction library:
import com.excelsior.xFunction.*;
...
/* Call Beep() from KERNEL32.DLL */
xFunction f =
new xFunction( "kernel32",
"int Beep(int,int)" );
f.invoke( new Argument(1770),
new Argument(100) );

Related

clone () implementation in Object class

I was reading this article and it says that
Object's clone method is very tricky. It's based on field copies, and it's "extra-linguistic." It creates an object without calling a constructor".
All I see in the grep code is the following line :
protected native Object clone() throws CloneNotSupportedException;
What am I missing here ?
You're missing the native which means it's implemented in non-Java code (in this case it's implemented in the JVM itself).
That's because the exact functionality of clone can not be implemented in Java code (which makes it so problematic).
The native keyword indicates that the implementation is in native (non-Java) code.
First of all, to actually understand the concept behind clone better I recommend the answer to the question: How to properly override clone method?
Regarding the source code you have put into your question:
native means here, that this is a method which is not implemented with Java, but with another language, often C or C++. It's still part of the JVM, hence you can find the actual implementation in the OpenJDKâ„¢ Source Release in the
"openjdk/hotspot/src/share/vm/prims/jvm.cpp":539
JVM_ENTRY(jobject, JVM_Clone(JNIEnv* env, jobject handle))
JVMWrapper("JVM_Clone");
Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
const KlassHandle klass (THREAD, obj->klass());
JvmtiVMObjectAllocEventCollector oam;
.
.
.
JVM_END
The method is marked as native, so you cannot see its implementation because it is not in Java.

Memory management using directors in SWIG C++ / Java

I am trying to create a Java wrapper for my C++ library using SWIG.
In order to get all the features I need within a Java programming environment, I need directors.
More specifically, I need Java users to be able to inherit from my C++ classes and implement certain methods.
In particular, one of the method that needs to be implemented is some sort of clone() method.
In C++, the user implementation provides an object pointer Base*. This pointer is then managed by the library itself.
Base* Derived::clone() {
return new Derived(*this);
}
The problem I have with the Java wrapper is that the Java proxy class for Base acquires the management of the corresponding C++ director class SwigDirector_Base, by default.
This is certainly suitable in the general case, but not in this particular user-defined clone() function.
My personal constraint is that the Java wrapper for my C++ library uses no Java-specific code, so the user implementation should look like:
class Derived {
...
Base clone() {
return new Derived(this);
}
}
So far, to make it work and avoid garbage collection of the copied Java instance, I have used the trick mentioned in http://www.swig.org/Doc2.0/SWIGDocumentation.html#CSharp_memory_management_member_variables.
And to make sure that the Java Derived class never deletes the corresponding C++ director class SwigDirector_Base, I have used %typemap(directorout) to set the value of the Java cMemOwn flag of the copied instance from the C++ wrapper code, that is in method SwigDirector_Base::clone().
I am not so happy with this solution as it applies to all methods returning a pointer to the Base class, whether it is a copy method or not...
Any idea on how to do this on a function-specific way? Or in any other way?

My Python-Java Interface, good design? And how to wrap JNI Functions?

I'm going to write my own Python-Java interface. It is compiled as a DLL and
wrapped using ctypes.
Yet, it is possible to find Java-classes and allocate Java-objects.
But what would be an interface to another language without using those objects
methods? My aim is to make this as natural as possible. Unfortunately,
it isn't just possible to find Java-methods only by name.
My model is the following:
JClass
An instance of this class represents a Java class.
JObject
An instance of this class represents a Java-object. It has to be
initialized with a JClass-instance. (yet, of course, later there
should be arguments for the constructor also.)
JMethod
Represents a method of a Java-object. It contains the name and signature of the desired method. The signature is evaluated dynamically by the classes that are given on initialization.
Example:
mainMethod = JMethod('main', JStringArray)
Note that JStringArray is an instance of JClass that represents a string-array.
A JMethod can be added to a JClass instance. But can then be called only from an instantiated JObject.
JStaticMethod
Just like the JMethod, but it can also be called from a JClass
instance.
Built-In types
I'm doing JInt, JShort, JLont, JChar, etc.. to be the
built-in wrapper types.
Like:
JInt = JClass('java/lang/Integer')
JShort = JClass('java/lang/Short')
JString = JClass('java/lang/String')
Question(s):
What do you think about this design?
The JNI-Functions for calling methods of a Java-class / -object all
take a variable amount of arguments. After reading several topics on
calling a function with variable arguments from a function that does so,
and also asked a question here on SO, I'm aware that this is not possible.
Now, are there functions that don't take a variable number of arguments
but a va_list or something? I just need to find some way to call a method from Python in Java!
1. What do I think of this design?
it's not clear what actual problem you're trying to solve.
what about edge cases; error-handling; forward-/backward-compatibility; bugs in Python/Java? Not fun, but essential for robust software.
mixing two languages is hard enough, mixing three is sure to be much much worse. I would expect major maintainability and coupling problems.
there are already solutions to these problems. RPC, for getting programs in different languages to talk to each other. Jython, for Java/Python interoperability. I believe, Jython even allows you to create Python objects in Java and vice versa directly. Clarifying any shortcomings of these existing systems, and how you would address these shortcomings, would be helpful.
Here are a few missing things:
packages
privacy
interfaces/abstract classes
method resolution: overloads and overrides(especially when more than one method would match)
exceptions
type-checking, or recovering from type errors
2. I just need to find some way to call a method from Python in Java! What about Jython, RPC, or just calling an executable?

Java/Ruby: is there a way to do .constantize or Object.send() in Java?

In Ruby, you can do "var1".constantize to get the actual variable var1.
Ruby also has Model.Send("method name, parameters can be here, etc"), and it would be the same as actually calling that method.
What I want to do.. is... kinda tricky... I want the string "var1 == var2" to be converted to actual variables in my java app, then evaluated.
Is there a way to do this?
Have you considered using JRuby?
As to your questions:
There is no peer to constantize that will allow for an eval like syntax where you can pass in a String and convert it to code in Java. You can do things like Class.forName to load a particular class from a String, but it doesn't sound that is what you are looking for.
You can use the Java reflection API to dynamically invoke methods on a class Check out Jakarta Commons BeanUtils for some utility methods that may help.
In Java, similar behaviour is achieved through the Reflection API. However, since Java is a compiled language, local variables' (within methods, constructors, parameters, etc) information is erased on compilation.
However you still have complete access to class names, hierarchies, methods and fields (class variables).
A good starting point is the Reflection API tutorial or the getClass() method of Object.
In Java if you want a dynamic lookup of variables, you would typically place them in a Map and lookup use the keys of that Map.
Can you explain what you are trying to do in more detail, I suspect what you are trying to do can be done simply a different way in Java.

Matlab / Java API callback

I'm designing an API (in Java) and expect to have users accessing the API from Matlab. The problem is that I want the API to provide a piece of functionality like:
javaApi.waitUntilPredicateIsTrue(Predicate<JavaObj> test);
My API (in the background) gets hold of instances of Java Obj (via some mechanism, e.g. polling). I want this API method to block until one of these instances, when passed to the Predicate evaluates to true. If I was calling this API from Java, I'd do:
javaApi.waitUntilPredicateIsTrue(new Predicate<JavaObj>() {
public boolean evaluate(JavaObj jo) {
return "READY".equals(jo.getState());
}
});
You get the idea.
How can this be called from within Matlab? Can I use anonymous inner classes from Matlab? Can I declare a Matlab classdef which extends the interface Predicate (can this cope with the Java generic version)?
That sounds like a tough question. I'm still running R2006b so this may have changed, but it looks like MATLAB will not translate function handles (incl. anonymous functions) and structures into Java objects. I don't know about MATLAB custom classes, since the syntax has changed. Strings, arrays, and cell arrays will translate properly. They don't comment at all on implementing interfaces. (:p :p :p BOO HISS)
edit: just found this page on Matlab Central, it talks about some undocumented interfaces.
Matlab has a much nicer solution than forcing users to create a whole class just to provide a single method. Take a look at their anonymous functions.
Note that anonymous functions in Matlab have odd scoping rules. Make sure you read the "Variables Used in the Expression" section of the linked help page. If you want more traditional lexical scoping, take a look at nested functions.
EDIT:
I am assuming that you will be doing the polling from Matlab, not passing the predicate function to Java. Example:
function waitForPredicate(pred)
while pred
end
end
waitForPredicate(#()javaApi.isMyConditionMet());

Categories

Resources