JNI native method

Say I create a JVM from native code and use it to popup a GUI... kinda like the next 2 lines:
res = JNI_CreateJavaVM(&jvm, (void **)&env, &vm_args);
mid = (*env)->GetMethodID(env, cls, "showWindow", "()V"); // This MID will pop up gui
Now, how do I make a button int he Java GUI call back down to the native code (C). Is this even possible without creating a shared library and doing System.loadLibrary() ?

See JNI function RegisterNatives. This lets you put native methods in your main executable rather than needing a shared library.
-slj-

Similar Messages

  • Access object attributes using other object JNI native method

    Hi. I'm trying to change an attribute of object O1 from another object O2 without invoking a O1 method and without making the attribute as public or protected.
    The only possibility that comes to my mind for doing so is writting a JNI native method
    public class O1 {
    static public native changeAttribute (Object O2, Object newAttributeValue) ;
    that change the attribute memory reference, but all I've found about accesing attributes in JNI is about accessing the invoker attributes (in this case, O1).
    �Does any one know if it's possible to do so? Thanks.

    I know that is not a good practice but I cannot figure out another way.
    I'll try to explain the whole problem so you see the reason. I'm working with transactions, using objects as the data. An object can be opened for write by several transactions because the granularity for conflicts is not the object, is each of its attributes. As long as two transaction don't write the same attribute, they both can write. For writing, each transactions uses a private copy of the object. At committing, the actual copy of the object must be replaced by the committer one, but as far as the granularity is the object attributes, only each written attribute must be replaced (if not, only the last commit would be visible).
    This attribute replace must be done by the transaction manager as far as the transactional object is provided by the client. So what i was thinking was to use JNI or some trick like that to replace the object attributes transparently to the object.
    I hope the explain is clear, my english is a little asleep :-(.
    How to do it with reflection? I thought that was only for method calling. Anyway, there wouldn't be problems if the attributes are private?
    Thanks for answering.
    EDIT: I've been able to change a public field using reflection, but not the private one
    import java.lang.reflect.*;
    class Caca {
    public static void main(String[] args) {
    Integer r = new Integer(0);
    System.out.println("original: " + r.toString());
    modifyWidth(r, 300);
    System.out.println("modified: " + r.toString());
    static void modifyWidth(Integer r, int newValue ) {
    Field valueField; Class c = r.getClass();
    try {
    valueField = c.getField("value");
    valueField.set(r, newValue);
    } catch (Exception e) { System.out.println(e); }
    Message was edited by:
    dfasdfsdafsadfasdf

  • JNI Calls to Native Methods No Longer Work: Possible Versioning Issue ?

    Hello, all. Just a quick question... is it possible that invoking a method in a JNI-compliant DLL from Java 6 will fail if the DLL's source was compiled against the JNI header files from Java 4 or 5 ? I have a DLL with methods that used to be called successfully (and now fail outright and don't even seem to be getting inside the native method), but it seems that the only thing that could have changed in the environment is the installed JRE. Even stranger, I don't get the hs_err* files anymore to indicate that the JVM crashed. Does anyone know why this might happen ? Thanks !

    Cthulhu76 wrote:
    Hello, all. Just a quick question... is it possible that invoking a method in a JNI-compliant DLL from Java 6 will fail if the DLL's source was compiled against the JNI header files from Java 4 or 5 ? Solely? No.
    You could of course be doing something in the JNI code in terms of working with Java which no longer works. Just as it is at least possible that java code from one version might not work with another.
    Correct error checking in the JNI code would at least correctly identify this problem however.
    I have a DLL with methods that used to be called successfully (and now fail outright and don't even seem to be getting inside the native method), but it seems that the only thing that could have changed in the environment is the installed JRE.The only thing that you assume changed was the JRE.
    You seem unsure whether the JNI is being called at all, so verifying that first would be a good idea.

  • Exception when creating instance of a class with native method by JNI

    I am trying to use JNI - I want to have a Java class Foo have a
    method, that is a native C function.
    I follow the Sun's tutorial
    http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jnie...
    exactly, and everything compiles fine, and I have compiled my C .dll
    as well (on Win XP). So I am ready to run - ...
    Now when I finally try to run the Java application, it throws this
    exception when it tries to create the Foo instance:
    at Foo.<init>(Foo.java:11)
    at
    sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at
    sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstruct
    orAccessorImpl.java:39)
    at
    sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingC
    onstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:
    513)
    at java.lang.Class.newInstance0(Class.java:355)
    at java.lang.Class.newInstance(Class.java:308)
    at sun.applet.AppletPanel.createApplet(AppletPanel.java:786)
    at sun.applet.AppletPanel.runLoader(AppletPanel.java:715)
    at sun.applet.AppletPanel.run(AppletPanel.java:369)
    at java.lang.Thread.run(Thread.java:619)
    Caused by: java.security.AccessControlException: access denied
    (java.lang.Runtim
    ePermission loadLibrary.Foo)
    Why would this be so??? Thank you for your insights

    Mark_Galeck wrote:
    I am trying to use JNI - I want to have a Java class Foo have a
    method, that is a native C function.
    I follow the Sun's tutorial
    http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jnie...
    exactlyNot quite exactly. Yours is an applet, theirs is an application.
    Applets are not allowed many things that applications can do.
    Among them, loading native libraries.

  • FATAL ERROR in native method: Non-array passed to JNI array operations

    After stepping up to JDK 1.4.2 we started getting a hotspot error, I added -Xcheck:jni and it yielded the above error which was not existent in JDK 1.4.1 and for the life of me I cannot find out whats wrong:
    Native method dec:
    private native byte[] cost(final byte[] byte_array,
    final double minCostPerMeter,
    final int costFuncSelection,
    final double maxCostThreshold);
    Method call:
    ByteArrayInputStream
    inputByteStream = new ByteArrayInputStream(
    cost(output_byte_stream.toByteArray(),
    minCostPerMeter,
    costFunctionSelection.length,
    maxCostThreshold));
    An array is being passed I have no idea why it is complaing about the method call.
    Any help would be appreciated.
    -R

    What happens if you remove all the code from the JNI method - so it just calls and then returns?
    If it still occurs then I would expect that you have a memory problem in a piece of code before this one. Such problems can have no impact when run in one environment but cause failures in another becomes some other legitimate piece of data moved.
    If it doesn't then I would expect that the problem is in the method itself and not the call.
    It could be some odd VM problem so trying a different version of 1.4.2 might help (but in of itself would not eliminate the possibility that you have a memory problem.)

  • JNI Unsatisfied Link Error at Runtime on Native method

    I wnat USe C functionality In My Java Program so that I Use JNI.In My Java Program i use dll file of c program using System.load("");.when iam compiling my Java Program it works Fine But When Iam Run My Java Program It Displays Unsatisfied Lik Error on Native method oh C Program.

    RAGHUKUMAR_KOLIKINENI wrote:
    I wnat USe C functionality In My Java Program so that I Use JNI.In My Java Program i use dll file of c program using System.load("");.when iam compiling my Java Program it works Fine But When Iam Run My Java Program It Displays Unsatisfied Lik Error on Native method oh C Program.As noted that requires a resolvable path - either it must be absolute or relative to the current working directory.
    However if you failed to load the library then you cannot get the error that you posted unless you are ignoring the exception from the load() call. And doing that is a bad idea.
    At least if the library is not loading.
    If it is loading then the method that you use to load it has nothing to do with your problem.

  • JNI-Can't access variables in native methods

    Hello,
    I wrote a simple JNI code in which the native method accesses an instance
    method, prints it and modifies it. The java method is names Sample.java
    and the native method is called Sample.c.
    The problem is I don't seem to get the variables correctly accessed in the
    native code. I am reproducing Sample.java, Sample.c and Sample.h. here. I
    am also reproducing the output.
    Please let me know if there are any mistakes..
    //Sample.java
    public class Sample
    int i;
    public native void modify();
    Sample()
    i = 10;
    System.out.println("In Java: i = "+ i);
    static
    System.loadLibrary("samp");
    public static void main(String [] args)
    Sample s = new Sample();
    s.modify();
    System.out.println("Again in Java: " +s.i);
    //Sample.c
    #include <jni.h>
    #include "Sample.h"
    #include <stdio.h>
    JNIEXPORT void JNICALL Java_Sample_modify(JNIEnv * env, jobject obj)
    jclass cls = (*env)->GetObjectClass(env, obj);
    jfieldID fid;
    jint ci;
    fid = (*env)->GetFieldID(env, cls, "i", "I");
    ci = (*env)->GetIntField(env, cls, fid);
    printf("Accessed in c\n: i = %d\n", ci);
    (*env)->SetIntField(env, cls, fid, 200);
    printf("modified in c\n i = %d\n", ci);
    //Sample.h
    /* DO NOT EDIT THIS FILE - it is machine generated */
    #include <jni.h>
    /* Header for class Sample */
    #ifndef IncludedSample
    #define IncludedSample
    #ifdef __cplusplus
    extern "C" {
    #endif
    * Class: Sample
    * Method: modify
    * Signature: ()V
    JNIEXPORT void JNICALL Java_Sample_modify
    (JNIEnv *, jobject);
    #ifdef __cplusplus
    #endif
    #endif
    and the output is
    In Java : i=10
    Accessed in c
    : i=196653
    modified in c
    i=196653
    Again in Java : 10
    Thanks,
    Aditya

    GetFieldID(..) expects an obj variable, not a cls. The
    obj passed in is a reference to the java object you
    are trying to modify, so you need to pass this to
    GetFieldID(..) etc.
    See below:
    JNIEXPORT void JNICALL Java_Sample_modify(JNIEnv *
    env, jobject obj)
    jclass cls = (*env)->GetObjectClass(env, obj); /// NOT
    REQUIRED
    jfieldID fid;
    jint ci;
    fid = (*env)->GetFieldID(env, cls, "i", "I"); // USE
    THE obj PASSED in NOT cls
    ...hope this helps :)Hi
    From what I got I modified the code as
    fid = (*env)->GetFieldID(env, obj, "i", "I");//obj instead of cls
    Well, the program kinda crashed :-(
    Moreover I used the same code I found in the jni tutorials on the sun website..which I reproduce. I noted that they used cls instead of obj.
    #include <stdio.h>
    #include <jni.h>
    #include "FieldAccess.h"
    JNIEXPORT void JNICALL
    Java_FieldAccess_accessFields(JNIEnv *env, jobject obj)
    jclass cls = (*env)->GetObjectClass(env, obj);
    jfieldID fid;
    jstring jstr;
    const char *str;
    jint si;
    printf("In C:\n");
    fid = (*env)->GetStaticFieldID(env, cls, "si", "I");
    if (fid == 0) {
    return;
    si = (*env)->GetStaticIntField(env, cls, fid);
    printf(" FieldAccess.si = %d\n", si);
    (*env)->SetStaticIntField(env, cls, fid, 200);
    fid = (*env)->GetFieldID(env, cls, "s", "Ljava/lang/String;");
    if (fid == 0) {
    return;
    jstr = (*env)->GetObjectField(env, obj, fid);
    str = (*env)->GetStringUTFChars(env, jstr, 0);
    printf(" c.s = \"%s\"\n", str);
    (*env)->ReleaseStringUTFChars(env, jstr, str);
    jstr = (*env)->NewStringUTF(env, "123");
    (*env)->SetObjectField(env, obj, fid, jstr);
    I may not have got your exact message :-(. But something seems to be wrong with yhe code and being a begining jni programmer, I am absolutely clueless:-(
    Any help would be appreciated :-)
    Thanks,
    Aditya

  • Error while compiling javacode with native method using jni

    im trying to call function in dll that is written in vc++ from java application.
    For that i write a native method .the method name is StopDS1.
    my native method is : public native DWORD StopDS1();
    when compiling using javac i'm getting message like this:
    testdss.java:4: cannot found symbol
    symbol:class dword
    location :class testdss
    1error

    DWORD isn't a Java type, therefore you cannot use it as one.

  • Returning several values from a C native method

    Hi,
    I need to return 3 values from a native methode : an int (the return code), a string of variable length and a double.
    In pure C, my function would be defined as "int f ( char* s, double* d)", and I would "malloc" the string into the calling function, then copy my string to "s" and use "*d" to return the double...
    Is there a way to do that with JNI? I found some examples where the native function returns only one parameterlike: "return(*env)->NewStringUTF(env, buffer);" But I didn't find examples where the native function returns several parameters, including a string.
    Thanks in advance!
    JM

    This really has nothing to do with JNI.
    You have a method, and you want to return more than one type of value.
    The following solutions are possible.
    1. Return an array that contains all the values (actual return value.)
    2. Return an object that contains all the values (actual return value.)
    3. Use an array via the parameter list and fill in a value.
    4. Use an object via the parameter list and fill in the values.

  • Accessing a native method from within a packaged class

    I have seen some very useful information from RPaul. However, I can not quite get it to work.
    I have a class "JNIGetUserId" that is in a package "com.services.localoptions". I am trying to call a native method from a dll. it works fine at the default package level. But not in the package. I have tried adding the "_" between each level of the directory in the h and c++ files. I also found that doing a javah at the top of the package structure it includes some information in the h file. A "_0005" shows up between each level.
    This is on Windows XP. I am also using VisualAge for Java. I also am using JDK 1.3.1.
    The source files:
    package com.services.localoptions;
    * This class provides the JNI Interface to call the
    * AD User Maintainence routines.
    * These routines are stored in the JNIGetUserIdLibrary.dll.
    * The routines are:
    * <ul>
    * <li>getUser - returns a string containing the User Id
    * <eul>
    * @author: Ray Rowehl
    * @date (10/15/2003 10:30:59 AM)
    public class JNIGetUserId
         // Load the library
         static
         try
              System.out.println("loading dll");
         System.loadLibrary("JNIGetUserIdLibrary");
         System.out.println("loaded dll");
         catch (UnsatisfiedLinkError ue)
              System.out.println("Link Error");
    * native C++ method to call getUserId routine
    public native String getUser() throws Exception;
    * This method allows us to test standalone..
    * Creation date: (10/16/2003 2:08:58 PM)
    * @param args java.lang.String[]
    public static void main(String[] args)
         try
              System.out.println("Trying method 3");
              JNIGetUserId lGUD = new JNIGetUserId();
              System.out.println(lGUD.getUser());
         catch (Exception e)
              System.out.println("Got an exception " + e);
              e.printStackTrace();
    /* DO NOT EDIT THIS FILE - it is machine generated */
    #include <jni.h>
    /* Header for class JNIGetUserId */
    #ifndef IncludedJNIGetUserId
    #define IncludedJNIGetUserId
    #ifdef __cplusplus
    extern "C" {
    #endif
    * Class: JNIGetUserId
    * Method: getUser
    * Signature: ()Ljava/lang/String;
    JNIEXPORT jstring JNICALL Java_com_localoptions_JNIGetUserId_getUser
    (JNIEnv *, jobject);
    #ifdef __cplusplus
    #endif
    #endif
    // Implements method to return a string to Java
    // C++ core header
    #include <iostream.h>
    // header from Java Interface
    #include "JNIGetUserId.h"
    #include "JNIGetUserId2.h"
    // returns a string back to Java for package structure
    JNIEXPORT jstring JNICALL Java_com_services_localoptions_JNIGetUserId_getUser
    ( JNIEnv * env, jobject thisObject )
         // set up constant user id for testing return
         char* userid = "RROWEHLP";
         // return userid to caller
         return env->NewStringUTF( userid );     
    // returns a string back to Java for flat structure
    JNIEXPORT jstring JNICALL Java_JNIGetUserId_getUser
    ( JNIEnv * env1, jobject thisObject1 )
         // set up constant user id for testing return
         char* userid1 = "RROWEHL1";
         // return userid to caller
         return env1->NewStringUTF( userid1 );     
    }

    Ok. A co-worker figured it out for me. The key thing is to do "javah com.services.localoptions.JNIGetUserId". Note the use of "." instead of "\". Running on windows, I was used to doing "\". That was part of the problem. Another key is doing the javah at the top of the package structure. This was mentioned in a post over at IBM.
    We got our JNI stuff working now. thanks, ray.

  • How to put native methods in jar file

    Hi.I have an executable jar file(test.jar) that makes use of other jar files and native methods. For example, test.jar uses Jnpout32.dll. . test.jar , the other jar files and the native methods are all in the same directory. When I created test.jar I wrote a manifest file which specifies the class path of the other jar files and the native methods as follows and provided it as an option in the jar cfmev command.
    Class Path: jdbc.jar Jnpout32reg.dll  //content of manifest.txt  file that I provided to the jar command
    //carriage return I then run the command java -jar test.jar to run the file.
    All I am seeing is the following error message
    Exception in thread "AWT EventQueue-o
    "Java.lang.NoClassDefFoundError.
    gnu/io/SerialPortEventListner"
    {code}
    Any ideas? thanks in advance!
    Edited by: Nostalgia on May 22, 2009 8:05 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    You seem to be confusing Java's classpath with your os's path. The classpath only applies to Java classes. See if this discussion helps:
    http://www.inonit.com/cygwin/jni/helloWorld/load.html

  • Unable to call a native method

    Hi All,
    I am trying to call a native method tapi3Init from tapi3.dll present in Windows\System32 folder. But I get an error as below.
    Exception in thread "Main Thread" java.lang.UnsatisfiedLinkError: DLLCall.tapi3Init
         at DLLCall.main(DLLCall.java:25)
    I have verified my java.library.path and it has the path in it. I have cross verified by typing a wrong dll name and that gave a relevant error. So, please let me know what is going wrong?
    Also, is it not possible to call a native method from a dll which is not formed by using the javah header file?
    Thanks.

    native method tapi3Init from tapi3.dllSo that would be your JNI method.
    Exception in thread "Main Thread" java.lang.UnsatisfiedLinkError: DLLCall.tapi3Init And you are not calling it. Standard reasons apply.
    - library not loaded
    - Signatures are different.

  • How to create new java objects in native methods?

    Hello,
    Is it possible to create java objects and return the same to the java code from a native method?
    Also is it possible to pass java objects other than String objects (for example, Vector objects) as parameters to native methods and is it possible to return such objects back to the java code?
    If so how can I access those objects (say for example, accessing Vector elements) inside the native code?
    What should I do in order to achieve them?
    Regards,
    Satish

    bschauwe is correct in that constructing Java objects and calling methods on Java objects from native code is tough and takes some study. While you're at it, you might want to check out Jace, http://jace.reyelts.com/jace. It's a free open-source toolkit that really takes the nastiness out of doing this sort of stuff. For example,/**
    * A C++ function that takes a java.util.Vector and plays around with it.
    public void useVector( java::util::Vector& vector ) {
      // Print out all the contents of the vector
      for ( Iterator it = vector.iterator(); it.hasNext(); ) {
        cout << it.next();
      // Add some new elements to the vector
      vector.addElement( "Hello" );
      vector.addElement( "world" );
    } All this code just results in calls to standard JNI functions like FindClass, NewObject, GetMethodID, NewStringUTF, CallObjectMethod, etc...
    God bless,
    -Toby Reyelts

  • How do I declare a native method outside of the main class?

    Hi
    This is a JNI particular question.
    I am having a problem with generating the header .h file after executing javah. The file is generated correctly but is empty under certain circumstances.
    This is the 'empty file:
    =================
    /* DO NOT EDIT THIS FILE - it is machine generated */
    #include <jni.h>
    /* Header for class gui_GuiMain */
    #ifndef Includedgui_GuiMain
    #define Includedgui_GuiMain
    #ifdef __cplusplus
    extern "C" {
    #endif
    #ifdef __cplusplus
    #endif
    #endif
    This is what it should look like:
    =========================
    /* DO NOT EDIT THIS FILE - it is machine generated */
    #include <jni.h>
    /* Header for class gui_GuiMain */
    #ifndef Includedgui_GuiMain
    #define Includedgui_GuiMain
    #ifdef __cplusplus
    extern "C" {
    #endif
    * Class: gui_GuiMain
    * Method: getValueOIDTestMIB
    * Signature: ()V
    JNIEXPORT void JNICALL Java_gui_GuiMain_getValueOIDTestMIB
    (JNIEnv *, jobject);
    #ifdef __cplusplus
    #endif
    #endif
    The header file becomes "empty" when the native function getValueOIDTestMIB is declared in a different class than what my main() function is declared in.
    For example something like this will work:
    class Main
    public native void getValueOIDTestMIB
    static {
    System.loadLibrary("libsnmp++");
    //............some more functions etc.............
    public static void main(String[] args)
    //............some more stuff...........................
    But when I declare this:
    public native void getValueOIDTestMIB
    static {
    System.loadLibrary("libsnmp++");
    outside the class, in another class within the same package, nothing happens.
    I am probabily doing something stupid. Can somebody help or give me some guidance to where I should look. I come from a C++ background, not a guru in Java.
    Thanks

    You need to run javah and give it as a parameter the full class name of the class which contains the native methods.
    For example (if your class is called A and its package is a.b.c)
    javah -jni a.b.c.A

  • How to use a C function as a native method

    Could anybody tell me how to use a C function as a Java native method.
    Thanks

    Read all about it.
    You'd probably have to write a little wrapper (using JNI) that passes
    parameters and return values around between your C function and
    the JVM.
    kind regards,
    Jos

Maybe you are looking for

  • How to read a message from com port

    i have a gsm modem connect to my pc though a serial port how can i read the output from modem and use them in my java program many thanks....

  • Want to download english version and remove dutch version without losing data

    hi, have been instructed to remove the dutch version without removing the personal data, there is however no option for doing that, there is just the uninstall option in windows 7.

  • Download Java JRE problem

    This is what I receive from a webpage: Important Notice You are required to install/enable Java JRE for processing PPS online payment. Please press "Download Java JRE" button to install/enable Java JRE Please press "Reload" button after installed the

  • Creating function without creating class

    we can write stand-alone functions in c/c++ (without creating class) that is not possible in c++. but somebody told me there is a way to do this in Java. i could not believe. he did not tell me the way. is it really possible ?

  • Need opinions on a VERY low end power supply handling a low end graphics card

    Greetings. I have acquired my father's old(old) HP Slimline S3400F and have intentions of turning it into a media computer. Problem : Due to the tiny form factor, it has an abysmal 160watt PSU. Inquiry : I know that most manufacturers FAR overstate t