Platform Invoke in SUN's Java
The most of Java developer does not use (maybe cannot use) JNI. Because this API is very low and complex in use. But in some type applications developers need to call Native functions from system or other libraries. And the only decision is to write JNI code or to use some tools like xFunctions, JNIWrapper, etc. which are not easy. Why SUN does not developed something like Platform Invoke, which main idea is 揹eclare?and "use"? For example, I want to call in C# function GetSystemMetrics I write code:
value class Win32 {
public
[DllImport("User32.dll")]
static int GetSystemMetrics(int);
enum class SystemMetricIndex {
// Same values as those defined in winuser.h.
SM_CXSCREEN = 0,
SM_CYSCREEN = 1
};
};
and call it
int main() {
int hRes = Win32::GetSystemMetrics( safe_cast<int>(Win32::SystemMetricIndex::SM_CXSCREEN) );
int vRes = Win32::GetSystemMetrics( safe_cast<int>(Win32::SystemMetricIndex::SM_CYSCREEN) );
Console::WriteLine("screen resolution: {0},{1}", hRes, vRes);
}
Very easy, semantic and syntax suitable to C#, no low level code like JNI.
So I tried to prove that the same can be done in Java and wrote my Platform Invoke for Java. In my API I can write as follows:
@NativeLibrary(name = "user32.dll")
public class User32Lib extends CNativeLibrary {
public static final int SM_CXSCREEN = 0;
public static final int SM_CYSCREEN = 1;
@NativeFunction(name = " GetSystemMetrics")
public native int GetSystemMetrics(int);
}
and in any Java method I can call this function:
User32Lib user32 = new User32Lib();
int hRes = user32.GetSystemMetrics(user32.SM_CXSCREEN );
int vRes = user32.GetSystemMetrics(user32.SM_CYSCREEN);
System.out.println("screen resolution: ?+ hRes + ?+ vRes);
In my API I added hidden marshal of arrays and simple data structures, explicit marshal (Marshal class) for complex data structures and Delegate class that makes Thunk for Java methods used as callbacks of native functions. I do not claim that in this case JNI will not be used. But the most Java developers will be able to write code without JNI use.
Message was edited by:
vitallis
Message was edited by:
vitallis
Message was edited by:
vitallis
Message was edited by:
vitallis
Message was edited by:
vitallis

