Win32/JNI/CWin(s)

Hi There,
I am very much a novice to JNI (In fact I've never used it; haven't had the need). I really really hope some kinds folks here will help me out! I know I should do my own research but the Win32 API/JNI is a broad topic and I don't want to
I have a task ahead of me. I need to accomplish the following:
Within my Java application (running in the Win32 JVM, compiled in Eclipse), obtain a list of String, Point pairs with the following data:
( Title of window, X,Y of window ) for all of the win32 'windows' currently running/shown on the taskbar.
The x,y need not take into consideration of the window is minimized... i.e. if it shows its 'normal' x,y even when minimized, that's okay.
If it's easy, I'd love a description of how this would work. All I need is a list of the windows and preferably their x,y coords. If the x,y position adds more complexity than you'd like to get into, then a window-list query would suffice.
Thanks!
-Ed

You will find all the JAVA and C sources, along with the .class and .dll files in here:
http://pages.infinit.net/bidule/jfbriere/findwindows.zip
I have builded it with JDK 1.4.2 and gcc 3.3.1 on cygwin.
The build file to create the native library is also included.
To test it, simply do at the console:
java Win32UtilTest

Similar Messages

  • An unhandled win32 exception occured in java.exe , While running JNI

    I'm trying to use JNI to call 3rd party VB DLL , like this
    JNI <> VC++ DLL <> VB DLL
    In VC++DLL ,I have function(named Open) that call 3 function in VBDLL
    I have tested c++ code this function (by copy it and paste in normal vc++ project) ,and It works !
    But when I call this function(Open) via JNI , I've got "An unhandled win32 exception occured in java.exe" by Visual Studio Just-in-Time Debugger !!
    I think the problem is in the 3rd function that I call in Open, because when I remove the 3rd function It doesn't raise any exception.
    Before I do this, I alrealdy test every function in VBDLL in VB Project , and they work fine (Include the 3rd function that I think It cause exception).
    Can anybody tell me what's going on here ?
    or anything that I can do to fine What cause this problem ?
    Thanks in advance ^^
    Edited by: voteforpedro on Sep 2, 2008 4:18 AM

    You either have a pointer problem or you are calling the 3rd party library in an unexpected fashion.
    In terms of testing the most likely reason is that it wasn't tested enough. Moving/changing code modifies the layout in memory which can expose previously hidden pointer problems.

  • JNI + existing LIBS [Win32]

    - C++
    - 2 existing *.lib files plus a bunch of *.h files
    - no access to the source code
    - very advanced libraries with custom classes/types
    Q: How to create a Java wrapper for those 2 libraries?
    I know that normally I would include 'jni.h' and add special keywords to the code, but:
    1. I have no access to the source
    2. I know it's very complex and I would drown trying to figure it out
    I greatly applreciate any help,
    --Snake                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    1) Check if SWIG ( http://www.swig.org ) can help you.
    2) If you can't use SWIG, try writing an "impedance matcher".
    Outline:
    C++ DLL -> require complex parameters for input / output
    Encapsulate heavily the methods, such that you can use less complex parameters (like XML strings) to the C++ methods. They could be callable from a plain old C program.
    If you can call the methods from a plain old C program, you probably can write the JNI wrapper as well.

  • Problem with JNI hello world

    I found some tutorial on SUN site on how to use JNI. I'm using Eclipse to compije Java and C (via Cygwin) files. Here are complete files:
    Hello.java:
    class Hello
         public native void sayHello();
         static
              try
              System.loadLibrary("hello");
              catch(Exception e)
                   System.out.println("exc");
         public static void main(String[] args)
              Hello h = new Hello();
              h.sayHello ();
    }Hello.c:
    #include <mingw/_mingw.h> //because there are some types needed for JNI
    #include <jni.h>
    #include "Hello.h"
    #include <stdio.h>
    JNIEXPORT void JNICALL Java_Hello_sayHello
      (JNIEnv *env, jobject obj)
         printf("Hello world!\n");
         return;
    }Makefile:
    hello.dll : Hello.o Hello.def
         gcc -g -shared -Wl,--kill-at -o hello.dll Hello.o hello.def
    Hello.o : Hello.c Hello.h
         gcc -c -g -I"$(JAVA_HOME)\include" -I"$(JAVA_HOME)\include\win32" Hello.c -o Hello.o
    Hello.h : Hello.class
         javah -jni Hello
    clean :
         rm Hello.h
         rm Hello.o
         rm hello.dllHello.def
    EXPORTS
    Java_Hello_sayHelloEverything goes well, but when I run java program it does nothin (it should print message, but it just exit without any error).I'm sure that it's something stupid, but I cant see what. Can anyone tell me what am I doing wrong?
    Thenks.

    Answer 1: yes, there was no problem. I compiled and started simple 'hello world' program from Cygwin and from WinXP console, and it worked well.
    Answer 2: This is weird, I changed code to this:
    Hello.java:
         public native int getInt();
              System.out.println("Returned int is " + h.getInt());Hello.c:
    JNIEXPORT jint JNICALL Java_Hello_getInt
      (JNIEnv *env, jobject obj)
         return 25;
    }It does not print anything. I started this program from Cygwin and from WinXP console, and from Eclipse. Only if I debug in Eclipse (step by step) I get:
    Returned int is 25and still I don't get Hello string printed (even if I go step by step). It looks like cygwin has some problem with OS. Do you have any idea what to do, I'm a bit confused?
    Thank you.
    Message was edited by:
    zly

  • JNI - How to use the error reporting mechanism?

    I've developed a C++ DLL which is loaded from a commercial Win32 application (not written by me) as a plug-in for external calculations. On its initialization the C++ DLL launches the Java VM via the JNI invocation interface. When the DLL functions are called by the application, they forward the calls to Java objects inside the Java VM, again via JNI invocation interface.
    This works well, but I have encountered a weird error.
    From Java I open a JFrame containing a JTextArea as small console for debug output messages. If I turn output to this debug console off (my printToConsole routine checks whether a boolean flag is set), the string concatenation operator may lead to a crash of the Java VM.
    For example, if in one of the Java functions called from the
    DLL via JNI invocation interface the following is the first statement,
    it leads to a crash of the Java VM and the application that loaded the C++ proxy DLL.
    String test=""+Math.random(); // String test not used later
    Interestingly, if I comment this statement out, the Java code works fine WITHOUT any crash. I've already thought about potential races and synchronization issues in my code, but I don't see where this is the case. And the string concatenation error fails as well, if I insert sleep() statements in front of it and at other places in the code. However, if I turn on log messages printed to my JFrame debug console (containing a JTextArea), the String concatenation works without problems.
    So maybe the JNI interface has a bug and affects the Java VM; I don't see where my JNI code is wrong.
    One problem is that I do not get any stdout output, as the C++ proxy DLL is loaded by the Windows application, even if I start the Windows application from the DOS command line (under Windows).
    Does anyone know how to use the error reporting mechanism?
    http://java.sun.com/j2se/1.4.2/docs/guide/vm/error-handling.html
    Is it possible that the JVM, when it crashes, writes debug information about the crash into a file instead of stdout/stderr?
    My C++ proxy DLL was compiled in debug mode, but the commercial application (which loaded the DLL) is very likely not.
    I do not know hot to find the reason why the String concatenation fails inside the Java function called from the C++ DLL via JNI.

    Yes, I've initially thought about errors in the C++ code too. But the C++ code is actually very simple and short. It doesn't allocate anything on the C++ side. It allocates a couple of ByteBuffers inside the Java VM however via JNI invocation interface calls of env->NewDirectByteBuffer(). The native memory regions accessed via the ByteBuffers are allocated not by my own C++ code, but by the program that calls my DLL (the program is Metastock).
    The interesting thing is that everything works fine if output to my debug console is enabled, which means that in the Java print routine getConsoleLoggingState() returns true and text is appended to the jTextArea.
    static synchronized void print(String str)
    { MetaStockMonitor mMon=getInstance();
    if ( mMon.getFileLoggingState() && mMon.logFileWriter!=null) {
    mMon.logFileWriter.print(str);
    mMon.logFileWriter.flush();
    if ( mMon.getConsoleLoggingState() ) {
    mMon.jTextArea1.append(str);
    Only if output to the JTextArea is turned off (ie. getConsoleLoggingState()==false), the crash happens when the FIRST statement in the Java routine called via JNI invocation interface is a (useless) String concatenation operation, as described above.
    String test=""+Math.random(); // String test not used later
    Moreover, the crash happens BEFORE the allocated ByteBuffer objects are accessed in the Java code. But again, if console output is turned on, it works stable. If console output is turned off, it works when the (useless) String concatenation operation is removed in the Java routine called from C++.
    I've already thought about potential races (regarding multiple threads), but this can be ruled out in my case. It almost appears as if the JVM can have problems when called by the invocation interface (I tested it with Java 1.4.2 b28).
    All the calls between C++ and Java go ALWAYS in the direction from C++ code to Java. Unfortunately, there is no special JRE version with extensive logging capabilities to facilitate debugging. And the problem is not easily reproducible either.
    JNIEnv* JNI_GetEnv()
    JNIEnv *env;
    cached_jvm->AttachCurrentThread((void**)&env,NULL);
    fprintf(logfile,"env=%i\n",env);
    fflush(logfile);
    return env;
    // function called by Metastock's MSX plug-in interface
    BOOL __stdcall createIndEngine (const MSXDataRec *a_psDataRec,
    const MSXDataInfoRecArgsArray *a_psDataInfoArgs,
    const MSXNumericArgsArray *a_psNumericArgs,
    const MSXStringArgsArray *a_psStringArgs,
    const MSXCustomArgsArray *a_psCustomArgs,
    MSXResultRec *a_psResultRec)
    a_psResultRec->psResultArray->iFirstValid=0;
    a_psResultRec->psResultArray->iLastValid=-1;
    jthrowable ex;
    jmethodID mid;
    JNIEnv* env=JNI_GetEnv();
    jobject chart=getChart(env, a_psDataRec);
    if ( chart==NULL) {
    return MSX_ERROR;
    jobject getChart (JNIEnv* env, const MSXDataRec *a_psDataRec)
    jthrowable ex;
    jmethodID mid;
    int closeFirstValid, closeLastValid;
    closeFirstValid=a_psDataRec->sClose.iFirstValid;
    closeLastValid=a_psDataRec->sClose.iLastValid;
    long firstDate, firstTime;
    if (closeFirstValid>=1 && closeFirstValid<=closeLastValid) {
    firstDate = a_psDataRec->psDate[closeFirstValid].lDate;
    firstTime = a_psDataRec->psDate[closeFirstValid].lTime;
    } else {
    firstDate=0;
    firstTime=0;
    jclass chartFactoryClass = env->FindClass("wschwendt/metastock/msx/ChartFactory");
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Cannot find class ChartFactory\n");
    printSBufViaJava(sbuf);
    return NULL;
    mid = env->GetStaticMethodID(chartFactoryClass, "getInstance", "()Lwschwendt/metastock/msx/ChartFactory;");
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Cannot find method ID for ChartFactory.getInstance()\n");
    printSBufViaJava(sbuf);
    return NULL;
    jobject chartFactory=env->CallStaticObjectMethod(chartFactoryClass, mid);
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Exception while calling ChartFactory.getInstance()");
    printSBufViaJava(sbuf);
    return NULL;
    mid = env->GetMethodID(chartFactoryClass, "getChartID", "(Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;IIIIIII)F");
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Cannot find method ID for ChartFactory.getChartID()\n");
    printSBufViaJava(sbuf);
    return NULL;
    jobject symbolBuf=env->NewDirectByteBuffer(a_psDataRec->pszSymbol, strlen(a_psDataRec->pszSymbol) );
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Cannot allocate symbolBuf\n");
    printSBufViaJava(sbuf);
    return NULL;
    jobject securityNameBuf=env->NewDirectByteBuffer(a_psDataRec->pszSecurityName, strlen(a_psDataRec->pszSecurityName) );
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Cannot allocate securityNameBuf\n");
    printSBufViaJava(sbuf);
    return NULL;
    jobject securityPathBuf=env->NewDirectByteBuffer(a_psDataRec->pszSecurityPath, strlen(a_psDataRec->pszSecurityPath) );
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Cannot allocate securityPathBuf\n");
    printSBufViaJava(sbuf);
    return NULL;
    jobject securityOnlineSourceBuf=env->NewDirectByteBuffer(a_psDataRec->pszOnlineSource, strlen(a_psDataRec->pszOnlineSource) );
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Cannot allocate onlineSourceBuf\n");
    printSBufViaJava(sbuf);
    return NULL;
    // Java Function call leads to crash, if console output is turned off and
    // the first statement in the Java routine is a (useless) string concatenation.
    // Otherwise it works stable.
    jfloat chartID=env->CallFloatMethod(chartFactory, mid, securityNameBuf, symbolBuf,
    securityPathBuf, securityOnlineSourceBuf, (jint)(a_psDataRec->iPeriod),
    (jint)(a_psDataRec->iInterval), (jint)(a_psDataRec->iStartTime),
    (jint)(a_psDataRec->iEndTime), (jint)(a_psDataRec->iSymbolType),
    (jint)firstDate, (jint)firstTime );
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Exception while calling ChartFactory.getChartID()");
    printSBufViaJava(sbuf);
    return NULL;

  • Error in converting the c/c++ file to java in JNI

    hi all
    i am new to jni in java programming.
    i[b] had success fully compiled the java class i.e.
    Sample1.java--->Sample1.class--->Sample1.h
    but when to
    Sample1.c-->Sample1.dll
    as shown below
    in the console i get this error
    C:\jdk1.4\bin>cl -Ic:\jdk\include -Ic:\jdk\include\win32 -LD Sample1.c -FeSample
    1.dll
    'cl' is not recognized as an internal or external command,
    operable program or batch file.

    i had search whole website through google for curl and java but no help as required.
    hey if please do not mind, i need it urgent, i am asking you my another problem in this thread and is related:
    curl,libcurl and java api.
    i compiled all the lib curl and imported into my code and code is as follows:
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.sql.*;
    import org.curl.*;
    import java.lang.*;
    class test
         public void curl_connect()
              Runtime     rt=Runtime.getRuntime();
              String ls_str="";
              try
                   String urlpath="www.yahoo.com";                    
                   String CreateProcess ="";               
                   System.out.println("inside cURL process");               
                   CreateProcess = "c:\\curl\\curl.exe https://" + urlpath;
                   Process pr = rt.exec(CreateProcess);
                   InputStream stderr = pr.getErrorStream();
                   InputStreamReader isr = new InputStreamReader(stderr);
                   BufferedReader br =new BufferedReader(isr);
                   String line = null;
                   while ((line = br.readLine())!= null )
                        System.out.println(line);
                   CurlGlue cg = new CurlGlue();
                   cg.setopt(CURL.OPT_WRITEFUNCTION, 2);
                   cg.setopt(CURL.OPT_VERBOSE, 3);
                   cg.setopt(CURL.OPT_FOLLOWLOCATION, 1);
                   cg.setopt(CURL.OPT_SSL_VERIFYPEER, 0);
                   cg.setopt(CURL.OPT_SSL_VERIFYHOST, 0);
                   cg.setopt(CURL.OPT_SSLCERTTYPE, "PEM");
                   cg.setopt(CURL.OPT_SSLVERSION, 3);
                   cg.setopt(CURL.OPT_HTTPPOST, 1);
                   int result = cg.setopt(CURL.OPT_URL,CreateProcess );
                   // post method
                   cg.setopt(CURL.OPT_POST, 1);
                   // IS THIS THE RIGHT WAY TO SET SIMPLE POST DATA?
                   cg.setopt(CURL.OPT_POSTFIELDS, "some post data");
                   // IS THIS THE RIGHT WAY TO SET COOKIE?
                   String cookieString= "";
                   if(cookieString != null)
                   cg.setopt(CURL.OPT_COOKIE, cookieString);
                   cg.perform();
              catch(Exception ee)
                   System.out.println("error traced");
                   ee.printStackTrace();
    class test1
         public static void main(String args[])
              try
                   test t12= new test();
                   t12.curl_connect();
              catch(Exception ee)
                   ee.printStackTrace();
    }                    can you tell me how to do further
    curl is used to fetch a page from the source website to destination website.
    when i run this api on my machine then message appeare is failed to link
    at the end i am getting this output
    <pre>
    inside cURL process
    Libraries loaded.
    * Closing connection #0
    Press any key to continue...
    </pre>
    Message was edited by:
    centurions

  • Wildcards in Classpath for JNI-Calls

    Is it possible to use wildcards in the classpath for KNI-Calls?
    I would like to use wildcard for jni-calls like for normal java-calls (java -classpath *.jar ...), but it is not working.
    JDK version is JDK 1.5.0 on Win32

    I would like to use wildcard for jni-calls like for normal
    java-calls (java -classpath *.jar ...), but it is not working.It would be the Shell, not Java doing the wildcard magic.
    You would have to do the globbing manually (or use any OS APIs, or 3rd party APIs).

  • Java APP inside a Win32 Window

    Hello,
    Q1: I need to embed a complete java swing application inside an existing win32 application window (I have the HWND of it).
    How to do this ?
    Q2: Is it possible to set the native Win32 parent window of a JFrame with JNI ?
    Cheers,
    Mik

    This can be done, but is a little complicated.
    Firstly create a subclass of Canvas, with the following native method
    JNIEXPORT jlong JNICALL MyCanvas_getWindowInfo( JNIEnv *env, jobject canvas )
         JAWT      awt;
         jlong   handle      = 0;
         // Get the AWT
         awt.version = JAWT_VERSION_1_3;
         if( JAWT_GetAWT( env, &awt ) == JNI_TRUE )
              // Get the drawing surface
              JAWT_DrawingSurface     *ds = awt.GetDrawingSurface( env, canvas );
              if( ds )
                   // Lock the drawing surface
                   jint lock = ds->Lock( ds );
                   if( (lock & JAWT_LOCK_ERROR) == 0 )
                        // Get the drawing surface info
                        JAWT_DrawingSurfaceInfo     *dsi = ds->GetDrawingSurfaceInfo( ds );
                        if( dsi )
    #if WIN32
                             JAWT_Win32DrawingSurfaceInfo *info   = (JAWT_Win32DrawingSurfaceInfo *)dsi->platformInfo;
                             handle = (jlong)GetParent( info->hwnd );
    #endif
                             // Free the drawing surface info
                             ds->FreeDrawingSurfaceInfo( dsi );
                        // Unlock the drawing surface
                        ds->Unlock( ds );
                   // Free the drawing surface
                   awt.FreeDrawingSurface( ds );
         return handle;
    }Next in C, do the following
    1. Create a JWindow.
    2. Make it visible.
    3. Add an instance of MyCanvas to the JWindow.
    4. Call the getWindowInfo method, which will return the window handle of the frame.
    5. Remove the instance of MyCanvas, of make it invisible.
    6. Reparent the frame window using SetParent( handleOfApp, frameHandle );7. Change the style of the frame so it doesn't think its a top level window SetWindowLong( frameWindow, GWL_STYLE, WS_CHILD );The last step is to simply add you java frame (or whatever) to this newly created window.

  • JNI bug?

    Hi,
    I hope this is an OK place to report bugs. The opening message on the forum
    points to the website for bug reporting, but that's only about support and
    I'm not looking for support, I just want to report a bug (I think).
    Anyway. I'm playing with JRocket 7 over Win2K sp3. The version string is:
    $ ./java -version
    java version "1.4.0"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0)
    BEA Weblogic JRockit(R) Virtual Machine (build
    7.0-1.4.0-win32-GARAK-20020830-1714, Native Threads, Generational Concurrent
    Garbage Collector)
    I'm using JNI and though most things seem to work OK with JRocket, I've
    found that using JNI to call java.lang.Class.getDeclaredMethods() on any
    class object will trigger a Null pointer exception. The attached program
    demonstrates this. If you compile it up, and then call it with the full
    path to the JVM.DLL then it tries to print the results of listing all the
    methods of java.lang.Class. With Sun's J2SDK 1.4.1 (and before), and IBM's
    1.2-style JDK, it works fine. Using JRocket it throws a
    NullPointerException. I'm using all default options for JRocket.
    I'm using the CallObjectMethodA() function with a NULL argument array to
    invoke the method ('cos that's what my real code does), but providing a real
    non-NULL array, or using the varags form, CallObjectMethod(), makes no
    difference.
    BTW, I'm finding a few other places where JR's JNI is inconsistent with
    Sun's (not necessarily bugs, though I think some are). Should I post them
    here ? Or email someone ? Or just keep 'em to myself ;-)
    -- chris
    [JNITest.zip]

    Staffan,
    I had a look at this and can confirm
    that this is indeed a problem in JRockit. Unfortunately there is no easy
    workaround other than calling Class.getDeclaredMethods() from a Javamethod
    instead of directly from JNI. Can you explain a bit more about your
    application and what you want to achieve?Thank for confirming the bug (which, incidentally also affects the other
    get[Declared]{Field/Method/Constructor/Class}[s] methods -- with the
    exception of getInterfaces(), for some reason).
    What I'm doing is using JNI to drive the JVM from Smalltalk. I'm using
    reflection to generate (on-the-fly) wrapper (Smalltalk) classes
    corresponding to Java classes and whose instances internally use JNI to
    invoke the Java methods, etc. So it's rather important that reflection
    actually works ;-)
    There's no great difficulty in setting up a forwarding Java class that
    invokes the reflection methods of java.lang.Class, and the forwarding
    class's methods can be invoked from JNI without problems, so I've been able
    to put together a patch that allows my stuff to work over JRockit.
    You asked about the other inconsistencies I've found. There are only 3 (now
    I've had a chance to analyse what I was seeing a bit better -- not to
    mention getting rid of a couple of bugs of my own...). None is especially
    important, and they are kind of esoteric too, but FWIW:
    The JNI DefineClass() method: Sun's implementation will accept NULL values
    for either or both of the name and the class loader. JRockit seems to get
    an access violation (this is on Windows) if given a NULL name, and
    apparently calls exit() if it is given a NULL class loader. I think that
    the Sun behaviour is better since both the name and the classloader are
    optional using the Java interfaces.
    Given a couple of Java classes:
    class Base
    Base(int i) {}
    Base(boolean b) {}
    class Derived
    extends Base
    Derived(int i) {}
    Attempting to use one of Base's constructors as if they were "inherited" by
    Derived acts differently on Sun and JRockit. Code like (I'm typing this off
    the top of my head):
    jclass derived = jnvEnv->findClass("Derived");
    jmethod mid = jniEnv->GetMethodID(derived, "<init>", "(Z)V");
    jvalue args[1];
    args[1].z = true;
    jobject new = jniEnv->CallConstructorA(derived, mid, args);
    will fail on Sun's VM since the call to GetMethodID() will fail with a
    NoSuchMethodError (correctly, I think) whereas JRockit will return a handle
    on the constructor with the same signature in the superclass. When that
    "inherited" constructor is then used the created object is of class Base,
    even though the constructor was invoked on Derived.
    Given the following:
    class Base { public static int ambiguous = 100; }
    interface Interface { int ambiguous = -100; }
    class Derived extends Base implements Interface { }
    Any reference to Derived.ambiguous from Java will trigger a compile-time
    error. However it is legal to do the equivalent from JVM bytecodes (a
    getstatic with class="Derived" name="ambiguous" type="I") and is defined (as
    I read the spec) to be -100. I.e. the JVM resolves the field reference to
    the interface. Under both the Sun and JRockit JVMs that works as expected.
    Doing the equivalent from JNI:
    jclass derived = jniEnv->findClass("Derived");
    jfield fid = jniEnv->GetFieldID(derived, "ambiguous", "I");
    jint value = jniEnv->GetStaticIntField(derived, fid);
    returns -100 on Sun's JVM (which is what I'd expect), but returns 100 on
    JRockit (which I think is wrong).
    Like I said, esoteric...
    Hope this helps.
    -- chris

  • JNI - make dll (fatal error LNK1181)

    I make a simple jni program ( it just print "Hello World" )
    but, when I compile this program I got a LINK error
    D:\JavaProjects\HW>cl -I c:\java\jdk1.3.1_01\include -I c:\java\jdk1.3.1_01\incl
    ude\win32 -I c:\java\jdk1.3.1_01\cinclude -LD helloworldimp.c -Fe hello.dll
    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 12.00.8804 for 80x86
    Copyright (C) Microsoft Corp 1984-1998. All rights reserved.
    Command line warning D4024 : unrecognized source file type 'hello.dll', object f
    ile assumed
    helloworldimp.c
    Microsoft (R) Incremental Linker Version 6.00.8447
    Copyright (C) Microsoft Corp 1992-1998. All rights reserved.
    /dll
    /implib:helloworldimp.lib
    /out:helloworldimp.dll
    helloworldimp.obj
    hello.dll
    LINK : fatal error LNK1181: cannot open input file "hello.dll"
    anyone knows this error? then, plz help me
    thanx

    using VC++6.0?
    I got the same problem when trying out the tutorial, check MSDN library on this error, in the C++ source code, you should change all pointers refering to java to how MSDN tells you is microsoft standard, the tutorial c code, maybe works correctly with other compilers or older versions of VC++ compilers.
    unfortunatly I lost my source code, only having the .dll file left otherwise I could show you

  • JNI: experience in creating DLLs with G++ (mingw32)?

    Hello.
    I'm trying to create a DLL:
    --------------/HelloWorld.cpp/------
    #include <jni.h>
    #include "HelloWorld.h"
    #include <stdio.h>
    JNIEXPORT void JNICALL
    Java_HelloWorld_displayMessage(JNIEnv *env, jobject obj)
    printf("Hello world!\n");
    return;
    I previously created 'HelloWorld.java'
    class HelloWorld
    public native void displayMessage();
    static
    System.loadLibrary("HelloWorldImp");
    I created 'HelloWorld.class'.
    I created the header file 'HelloWorld.h':
    c:> javah -jni HelloWorld
    But I do not have any idea to create the DLL.
    I tried with:
    c:> g++ -I"D:\j2sdk\include" -I"D:\j2sdk\include\win32" HelloWorld.cpp -shared -o HelloWorldImp.dll
    But I get this error message when calling from 'Main.java':
    Exception in thread "main" java.lang.UnsatisfiedLinkError: displayMessage
    at HelloWorld.displayMessage(Native Method)
    at Main.main(Main.java:6)
    In order to get this message I created 'Main.java':
    class Main
    public static void main(String[] args)
    HelloWorld hello = new HelloWorld();
    hello.displayMessage();
    Does anybody have any experience in creating DLLs with G++???
    Thank you very much.

    Or is it better GCC?

  • Jni.h file not found???

    I am totally new to JNI Technology. I am trying to compile and run the HeloWorld Programme from the Tutorial.once i compile java file and .c file and try to build a Dynamic Link Library using the command
    cl -Ic:\java\include -Ic:\javainclude\win32 _LD HelloWorldImp.c -Fehello.dll..it gives one error.
    HelloWorldImp.c(1) : fatal error C1083: Cannot open include file: 'jni.h': No such file or directory.
    Is it that i have to compile HelloWorld.h first before i perform above command. If so how do i copile the .c File

    Hi,
    Yes u have to first make a heaher file...
    Suppose ur java prog is hello.java,
    then on command prompt write
    javah -jni hello it will result
    in a hello.h file
    Sheeba

  • JNI with GCC

    I use java1.4.2_01 on a win98 (don't ask) machine.
    I am trying to run an "hello world" app with the method in C. The code is identical to that given here, http://java.sun.com/docs/books/tutorial/native1.1/stepbystep/index.html.
    My code works, if the .dll is generated instead with a colleague's Microsoft Visual compiler. I am asking, then, if there are known issues with using Cygwin and GCC 3.3.1cygming to generate the .dll. This is my commandline (prettified here) when running gcc:
    BASH-2.05b$ gcc -mno-cygwin -shared
    -I/c/j2sdk1.4.2_01/include
    -I/c/j2sdk1.4.2_01/include/win32
    -o hello.dll hello.cI have hex-viewed the .dll thus generated and found that it is actually a .dll (as opposed to an .so), but I don't have the reverse-engineering skills to find out anything more.
    Oh yes, the Java error is at run-time when the .display() method is called and is:
    Exception in thread "main" java.lang.UnsatisfiedLinkError: test
            at TimTest.test(Native Method)
            at TimTest.main(TimTest.java:10)

    I am a little confused.
    You say that "extern C" should solve the problem. Am I correct in inferring that if I wrote C (not C++) code and compiled it as C code, this should never have come up?
    If I am correct there, then I would agree that the compiler might be `broken', or at least awkward. (As I had the same problem with JNI when I C-compiled C code.)
    If I'm not correct, please explain why "extern C" should produce no-mangling behavior. (my current understanding is that "extern C" is a directive saying "Treat the enclosed as C code.")
    Thanks.

  • Creating a shared library for JNI in windows

    I went through the JNi tutorial online and it worked just fine on a Linux computer. Now I'm trying to make do the same tutorial on windows. When I get to the step 4. Create a Shared Library, I'm stuck. I don't know how to create this shared library on windows. It gives an example using Visual C++ but I don't have that. Any tips or advice out there what I should do? Any help would be greatly appreciated.

    //mac.java
    class mac
        public native void getMac();
        private native String getLine(String prompt);
        static {
         System.loadLibrary("myMac");//This is myMac.DLL
         /*if generated by borland
         System.loadLibrary("mymac");//This is mymac.dll
         public static void main(String[] args)
        mac mc=new mac();
        String input = mc.getLine("Enter Some Thing ");
        System.out.println("You Entered " + input);
        System.out.println(mc.getMac());
    prompt> javac mac.java
    prompt> javah -jni mac
    Borland compiler
    /*mymac.c*/
    #include <jni.h>
    #include "mac.h"
    #include <stdio.h>
    JNIEXPORT void JNICALL
    Java_mac_getMac(JNIEnv *env, jobject obj)
        printf("I am in  getmac dir in mymac.dll (Borland) \n");
        return;
    JNIEXPORT jstring JNICALL
    Java_mac_getLine(JNIEnv *env, jobject obj, jstring enter)
        char buf[128];
        const char *str = (*env)->GetStringUTFChars(env, enter, 0);
        printf("%s", str);
        (*env)->ReleaseStringUTFChars(env, enter, str);
        scanf("%s", buf);
        return (*env)->NewStringUTF(env, buf);
    To generate DLL
    create bcc32.cfg file in %BORLAND_INSTALL%/BCC5/bin Folder
    In the bcc32.cfg file add following code
    -I"%BORLAND_INSTALL%\BCC55\include;%JAVA_HOME%\include;%JAVA_HOME%\include\win32"
    -L"%BORLAND_INSTALL%\BCC55\lib;%BORLAND_INSTALL%\BCC55\Lib\PSDK;"
    i.e the path for borland compiler and java.
    now goto prompt and say
    prompt>bcc32 -tWM -tWD mymac.c
    This will create mymac.lib File
    Now say
    prompt>implib -c mymac.lib mymac.dll
    That's it!!
    there you are with dll
    Now you can run the mac.class file by using java
    VC++
    Click File->New->Win32Dynamic-Link Library
    Give name and Select
    A simple DLL project
    You will have
    myMac.CPP file
    // myMac.cpp : Defines the entry point for the DLL application.
    #include "stdafx.h"
    #include "mac.h"
    #include "jni.h" //can copy or give full path
    #include <math.h>
    BOOL APIENTRY DllMain( HANDLE hModule,
                           DWORD  ul_reason_for_call,
                           LPVOID lpReserved
        return TRUE;
    JNIEXPORT void JNICALL
    Java_mac_getMac(JNIEnv *env, jobject obj)
        printf("You are in getMac (VC++) DLL\n");
    JNIEXPORT jstring JNICALL
    Java_mac_getLine(JNIEnv *env, jobject obj, jstring enter)
        char buf[128];
        const char *str = env->GetStringUTFChars(enter, 0);
        printf("\n%s", str);
        env->ReleaseStringUTFChars(enter, str);
        scanf("%s", buf);
        return env->NewStringUTF(buf);
    Hope this is useful
    regards
    kanad Deshpande

  • Calling an external C function from a C file in JNI

    Hello,
    I am trying to call an external C function, from a C file which is being called by a Java file. I am getting an unresolved symbol error. I have tried many things like, making the external C function in the format of JNI, etc, etc. It is still not working. I think it has something to do with linking the two C files. If anyone can please answer this, it would greatly help me. here is the code:
    HelloWorld.c:
    #include <jni.h>
    #include <stdio.h>
    #include "MyOldHello.h"
    #include "HelloWorld.h"
    JNIEXPORT void JNICALL
    Java_HelloWorld_print(JNIEnv *env, jobject obj)
         helloPrint();
         return;
    HelloWorld.java:
    class HelloWorld
         private native void print();
         public static void main(String[] args)
              new HelloWorld().print();
         static
              System.loadLibrary("HelloWorld");
              System.loadLibrary("MyOldHello");
    MyOldHello.c:
    #include <jni.h>
    #include <stdio.h>
    #include "MyOldHello.h"
    void helloPrint()
         printf("\nHello World!\n");
    MyOldHello.h:
    void helloPrint();
    Now i use the Visual C++ command prompt to compile this by saying:
    javac HelloWorld.java
    javah -jni HelloWorld
    cl -Ic:\Java\jdk1.6.0_20\include -Ic:\Java\jdk1.6.0_20\include\win32 -MD -LD HelloWorld.c -FeHelloWorld.dll
    and now it gives me the error saying that there is an unresolved external symbol, which is the call to helloPrint in the file HelloWorld.
    If anyone knows how to solve this, or how to call external C functions from a C file that is being called from a Java file using JNI, please respond.
    Thanks
    Nick

    Hi,
    In your post on velocity review, you did not compile MyOldHello.c. You compiled a C file that included the header file for it and called a method defined in the header. The linker is never going to be able to find the code for this if you do not include the object file for this.
    Try this. You will also have to add in any JNI libraries you need to link against but I am sure you could work that out.
    cl /c MyOldHello.c
    cl /c -Ic:\Java\jdk1.6.0_20\include -Ic:\Java\jdk1.6.0_20\include\win32 -MD HelloWorld.c
    cl /LD MyOldHello.obj HelloWorld.obj /FeHelloWorld.dll
    [http://msdn.microsoft.com/en-us/library/f35ctcxw(VS.80).aspx]
    Cheers,
    Shane

Maybe you are looking for

  • SAP R/3 -- PI -- Oracle DB SYNC (JDBC)

    What is the best approach to handle the following request: We need to develop a synchonous call that will pass information from SAP R/3 through PI to an Oracle database can return the data. For instance, we want to pass a material number from SAP R./

  • I forgot my 3g pass word how do i access?

    My 3 G iPhone is disabled - cannot access the key pad , lost four digit access code , can get incoming calls

  • How can i get my photos from iPhoto on snow leopard to lion?

    I had to have my photos restored from my old mac. I was running SL. I have them on an external drive. Have the mini now with lion and want to know how to get my photos! Help!

  • Copy Objects in OO ABAP.

    Hi, data: o_pricecond type zpricecond_struct. data: o_pricemat type zpricematerial_struct. ..some code for filling objects. I now have 2 different objects . I want to copy all fields from one object to another. The field names are the same... This gi

  • GL Interface Journal

    I am new to Oracle and the boss has given me a project to reconcile the GL Interface to our Billing Journals. What I need to know is just where does the data on the Interface come from (what is the criteria)because it seems pretty "here and there"...