Calling back c++ method in an exe (not a dll) from java?

Hi all,
I have to make an hybrid C++/java from an existing C++
application that compiled is a big single exe not a dll.
I'm running under win32.
The application consists of several windows. The hybrid
will have widows in C++ and some in java. They have the
same menu and tool bar. In the C++, there are some
callbacks called when a button is pressed. How to call
these callback from java given the fact that the JVM and
the java classes are launched by the exe file.
I know how, from C++, start JVM and call my java window.
I also know how to call a C++ method that is in a dll from
java. It's from the tutorial
http://java.sun.com/docs/books/tutorial/native1.1/index.html
But I don't know how to call a C++ method that is in in an
exe which has launch a JVM from an object running in this
JVM.
Is there somewhere an example like this?
Thanks,
Xavier.

Thanks this helped.
For those who want a complete example, here it is:
Tested on XP, java 1.4.2, VC++ 6.0.
************ File invoke.cpp *****************************
#include <stdlib.h>
#include <jni.h>
#ifdef _WIN32
#define PATH_SEPARATOR ';'
#else /* UNIX */
#define PATH_SEPARATOR ':'
#endif
#define USER_CLASSPATH "." /* where Prog.class is */
void JNICALL displayHelloWorld(JNIEnv *env, jobject obj)
    printf("Hello world: made by printf from C++\n");
    return;
void main() {
    JNIEnv *env;
    JavaVM *jvm;
    JavaVMInitArgs vm_args;
    jint res;
    jclass cls;
    jmethodID mid;
    jstring jstr;
    jobjectArray args;
    char classpath[1024];
     int result;
    /* IMPORTANT: specify vm_args version # if you use JDK1.1.2 and beyond */
     JavaVMOption options[3];
     options[0].optionString = "-verbose:gc";
     sprintf (classpath, "-Djava.class.path=%s", USER_CLASSPATH);
     options[1].optionString = classpath;
     options[2].optionString = "-Djava.compiler=NONE";
     vm_args.options = options;
     vm_args.nOptions = 3;
     vm_args.ignoreUnrecognized = JNI_TRUE;
        vm_args.version = JNI_VERSION_1_4;
     /* IMPORTANT: Note that in the Java 2 SDK, there is no longer any need to call
      * JNI_GetDefaultJavaVMInitArgs. It causes a bug
    /* Append USER_CLASSPATH to the end of default system class path */
    /* Create the Java VM */
    res = JNI_CreateJavaVM(&jvm,(void**)&env, &vm_args);
    if (res < 0) {
        fprintf(stderr, "Can't create Java VM\n");
        exit(1);
    cls = env->FindClass("mypackage/Prog");
    if (cls == 0) {
        fprintf(stderr, "Can't find mypackage/Prog class\n");
        exit(1);
   JNINativeMethod nm;
   nm.name = "displayHelloWorld";
   /* method descriptor assigned to signature field */
   nm.signature = "()V";
   nm.fnPtr = displayHelloWorld;
   env->RegisterNatives(cls, &nm, 1);
    mid = env->GetStaticMethodID(cls, "main", "([Ljava/lang/String;)V");
    if (mid == 0) {
        fprintf(stderr, "Can't find Prog.main\n");
        exit(1);
    jstr = env->NewStringUTF(" from C++! calleded by C++, using argument from C++ but java method");
    if (jstr == 0) {
        fprintf(stderr, "Out of memory\n");
        exit(1);
    args = env->NewObjectArray(1,
                        env->FindClass("java/lang/String"), jstr);
    if (args == 0) {
        fprintf(stderr, "Out of memory\n");
        exit(1);
    env->CallStaticVoidMethod(cls, mid, args);
    jvm->DestroyJavaVM();
}********************* File ./mypackage/Prog.java **************************
package mypackage;
public class Prog {
       public native void displayHelloWorld();
    public static void main(String[] args) {
        System.out.println("Hello World" + args[0] +"\n");
        Prog prog = new Prog();
        prog.displayHelloWorld();
        System.out.println("(called from java)");
        System.out.println("\nSo to sumurize:");
        System.out.println(" -1 Starting point is an exe (not DLL, there is no DLL) so C++ code");
        System.out.println(" -2 From C++ call java method using argument from C++");
        System.out.println(" -3 From java, that was launched by the exe, call to");
        System.out.println("    a native using the RegisterNatives in C++\n");
        System.out.println("You got a bidirectional example with as starting point");
        System.out.println("a single exe, launching JVM, loading class call back C++!");
}******************* Command line for all ****************************************
javac mypackage/Prog
cl -I"D:\Program Files\j2sdk1.4.2_03\include" -I"D:\Program Files\j2sdk1.4.2_03\include\win32" -MT
invoke.cpp -link D:\PROGRA~1\j2sdk1.4.2_03\lib\jvm.lib
(Remark, the last path is using the short name for "Program Files" because with the blank
even adding double quotes result into an error)
You must have jvm.dll in your path for me it's Path=D:\Program Files\j2sdk1.4.2_03\jre\bin\client;
Then simply call invoke and see the result. :-)

Similar Messages

  • How to call backing bean method from java script

    Hi,
    I would like to know how to call backing bean method from java script.
    I am aware of serverListener and [AjaxAutoSuggest article|http://www.oracle.com/technology/products/jdev/tips/mills/AjaxAutoSuggest/AjaxAutoSuggest.html]
    but i am running in to some issues with [AjaxAutoSuggest article|http://www.oracle.com/technology/products/jdev/tips/mills/AjaxAutoSuggest/AjaxAutoSuggest.html]
    regarding which i asked for help in other thread with subject ....Question on AjaxAutoSuggest article (Ajax Transactions Using ADF and J...)
    The reason why i posted is ( though i realise both are duplicates) .. that threads looks as a specific question to that article hence i would like to ask the quantified problem is asked in this thread.
    So could any please letme know how to call backing bean method from java script
    Thanks
    Murali
    Edited by: mchepuri on Oct 24, 2009 6:17 PM
    Edited by: mchepuri on Oct 24, 2009 6:20 PM

    Hello,
    May know how to submit a button autoamtically on onload of page with clicking a welcome alert box. the submit button has managed button too to show a message on console using SOP.
    the problem is.
    1. before loading the page a javascript comes on which i clicked ok
    2. the page gets loaded and the button is there which gets automatically clicked and the managed bean associated with prints a message on console using SOP.
    I m trying to do this through server listener and click listener. the code is(adf jspx page)
    <?xml version='1.0' encoding='UTF-8'?>
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
    <jsp:directive.page contentType="text/html;charset=UTF-8"/>
    <f:view>
    <af:document id="d1" binding="#{backingBeanScope.backing_check4.d1}">
    <af:form id="f1" binding="#{backingBeanScope.backing_check4.f1}">
    <af:commandButton text="commandButton 1"
    binding="#{backingBeanScope.backing_check4.cb1}"
    id="cb1" action="#{beanCheck4.submit1}"/>
    <af:clientListener type="click" method="delRow"/>
    <af:serverListener type= "jsServerListener"
    method="#{backingBeanScope.backing_check4.submit1}"/>
    <f:facet name="metaContainer">
    <af:resource type ="javascript">
    x=confirm("hi");
    // if(x){
    delRow = function(event){
    AdfCustomEvent.queue(event.getSource(), "jsServerListener", {}, false);
    return true;
    </af:resource>
    </f:facet>
    </af:form>
    </af:document>
    </f:view>
    <!--oracle-jdev-comment:auto-binding-backing-bean-name:backing_check4-->
    </jsp:root>
    the backing bean code is -----
    public class classCheck4 {
    public classCheck4() {
    public String submit1() {
    System.out.println("hello");
    return null;
    }

  • Is there any way to get back my data if I had not restored it from time machine before reinstalling Mac OS X on my comp from utility. PS - My OS version has downgraded from Mountain Lion to Mac OS X 10.75  . Pls. help

    Is there any way to get back my data if I had not restored it from time machine before reinstalling Mac OS X on my comp from utility. PS - My OS version has downgraded from Mountain Lion to Mac OS X 10.75  . Pls. help

    Look at the blue box on this link:
    http://pondini.org/TM/19.html
    Ciao.

  • Fall into a trouble when calling a dll from java in linux

    Hi, experts:
    I encountered a big trouble when using JNI to call a C++-compiled DLL from java in Linux: The DLL function didn't execute immediately after the invocation, and was deferred till the end of the Java execution. But all worked well after migrating to windows. This problem made me nearly crazy. Can somebody help me? Thanks in advance.
    Linux: fedora core 8, jdk1.6.0_10,
    compile options: g++ -fPIC -Wall -c
    g++ -shared

    It looks like the OP compiled the C source file and linked it into a Windows .dll, which would explain why it worked flawlessly in Windows. (Though I must say the usage of GCC would make someone think it was compiled in Linux for Linux, GCC also exists for Windows, so I'm not sure it's a Windows .dll either...)
    @OP: Hello and welcome to the Sun Java forums! This situation requires you to make both a .dll and a .so, for Windows and Linux. You can then refer to the correct library for the operating system using System.loadLibrary("myLibrary"); without any extension.
    s
    Edited by: Looce on Nov 21, 2008 11:33 AM

  • To call a VB dll from java

    Hi,
    I want to know how one can call a VB dll from Java.I know it is something like calling a C dll which in turn calls the VB dll.I also went through the tutorial provided on the sun site and was able to call a C dll through java but I still do not know how to call a VB dll from java.
    regards,
    Anshuman

    Have you checked google?
    First hit. Reply 17.

  • How to call backing bean method when user tabs out of af:inputListOfValues field

    Hi,
    I am using jdev 11.1.2.4.
    I want to call a backing bean method based on the value selected in the af:inputListOfValues field.
    The requirement is similar as Frank Nimphius-Oracle has demonstrated here  https://blogs.oracle.com/jdevotnharvest/entry/how_to_notify_the_server but with Input List of Values component.
    The fields I want to call method from is
    <af:inputListOfValues id="appealNameId"
                          popupTitle="Search and Select: #{bindings.AppealName.hints.label}"
                          value="#{bindings.AppealName.inputValue}"
                          label="#{bindings.AppealName.hints.label}"
                          model="#{bindings.AppealName.listOfValuesModel}"
                          required="#{bindings.AppealName.hints.mandatory}"
                          columns="#{bindings.AppealName.hints.displayWidth}"
                          shortDesc="#{bindings.AppealName.hints.tooltip}"
                          binding="#{backingBeanScope.backing_Donation.appealNameId}"
                          autoSubmit="true" clientComponent="false">
                          <f:validator binding="#{bindings.AppealName.validator}"/>
                          <af:autoSuggestBehavior suggestedItems="#{backingBeanScope.backing_Donation.onSuggestAppeal}"/>
                          <af:clientListener method="onBlurTxtField" type="blur"/>
    </af:inputListOfValues>
    <af:serverListener type="onBlurNotifyServer"
                       method="#{backingBeanScope.backing_Donation.onBlurNotify}"/>
    as you can see,  af:serverListener is outside the af:inputListOfValues which probably is the reason its not executing this method?
    public void onBlurNotify(ClientEvent clientEvent) {
       // get a hold of the input text component
       RichSelectOneChoice inputTxt =  (RichSelectOneChoice) clientEvent.getComponent();
       //do some work on it here (e.g. manipulating its readOnly state)
       //Get access to the payload
       Map  parameters = clientEvent.getParameters();
       System.out.println("SubmittedValue = "+parameters.get("submittedValue"));
       System.out.println("LocalValue =  "+parameters.get("localValue"));
    I've tried to put serverListener tag inside the <af:inputListOfValues> but getting below error
    "Server Listener is not valid child of Input List of Values"
    any ideas please?
    thanks

    As first, check to see that you are using correct type for af:serverListener (thet one you are queue in the javaScript onBlurTxtField function)
    If still does not work, go to directly to the page source code, and put af:serverListener "by hand", as a child for af:inputListOfValues.
    Because it is possible that these messages are false alarm...

  • Calling backing bean method from HttpSessionListener

    Hi,
    I am detecting session expiration through HttpSessionListener's sessionDestroyed() method. I have a logout() method in my backing bean which does all the session clean up. If the user clicks the logout link, then I call the logout method and do the clean up. But when the user closes the browser, then I believe that the HttpSessionListener's sessionDestroyed() method will be called. How do I call the logout() method of my backing bean from from sessionDestroyed() method of HttpSessionListener.

    I did as you said, but the finalize method is never called. I can see the session timing out and sessionDestroyed() method being called, but not the finalize() method. Here is the code for sessionDestroyed()
        public void sessionDestroyed(HttpSessionEvent sessionEvent){
            System.out.println("Session Destroyed Called");
            HttpSession session = sessionEvent.getSession();
            session.invalidate();
            System.gc();
        }and for finalize()
        public void finalize() throws Throwable{
            System.out.println("In Finalize Method");
            FacesContext ctx = FacesContext.getCurrentInstance();
            Object requestObject = ctx.getApplication().getVariableResolver().
                                   resolveVariable(ctx, "databaseCon");
            DatabaseCon databaseCon = (DatabaseCon) requestObject;
            Connection con = databaseCon.getConnection();
            String sql = "DELETE FROM TEMP WHERE EX_ID = ?";
            PreparedStatement pstmt = con.prepareStatement(sql);
            pstmt.setInt(1,this.getExId());
            pstmt.executeUpdate();
            super.finalize();
        }

  • ADF Faces Declarative Component onLoad event call Backing Bean Method

    Hello.
    We are trying to implement a declarative component, that will be used as Flex Fields for our application, ie, the components will be created dynamically through a database configuration, and who is responsible for organizing and creating the components, is the declarative components, and its own backing bean.
    The declarative component, will receive a List of custom components, and with this list it is possible to create the components dynamically. We want the components to be created as soon as the page is loaded. The developer could place this declarative component in any region of his page, and even in another tab if he wishes. The problem is, that we cannot register a load event in the declarative component, since it doesn't have a document Object, to call the declarative components backing bean method that is responsible for creating components.
    How could we simulate the onLoad (of the declarative components) so that the backing bean method (responsible for creating component, and putting it in the view tree) could be called ?
    I've tried with a RENDER_RESPONSE phaseListener, but the beforePhase has no objects in the tree, and the afterPhase has already rendered to the client.
    Any ideas on how to achieve this ?
    Thanks a lot.
    Regards,
    John

    Hi Frank, thanks for the response.
    I'm curious about the dynamic declarative component. Any place I could check it out ?
    Back to my scenario. I'll try to be more clear to what we need!
    We have to have dynamic creation of components, based on a database configuration. This will allow our customers to have custom flex fields, without the need of us developing custom pages for each customer.
    One solution we are trying out, is the declarative component. Why ? Because the developer (when developing the page), knows that this specific page, is possible of customization by the client (custom flex fields). With this, the developer would choose where on his page the custom flex fields will be placed. Note that at this point (design time), no component (input, buttrons, etc) is created. The idea of the declarative component, is just so the Developer knows where he wants the custom fields placed in his page (a tab, below the form fields, in a another panel group, and so on). The declarative component, has only a container, PanelFormLayout, and no other component.
    What we want, is a way of calling our managed bean (the managed bean of the declarative component, that now I did configure it in the adfc-config.xml file , thanks for the tip) method, that's responsible for creating the custom components. The declarative component, receives a list of all the custom fields that needs to be created, at design time, through an attribute. The developer is responsible for setting this list when he drags the declarative component on his page.
    Now that I've put the declarative components managed bean in the adfc-config.xml file, the @PostConstruct is called correctly, but I still have a problem. At this moment (postContstruct call), my component PanelFormLayout (that is binded to the managed bean), is null. So I cannot add any component to the PanelFormLayout.
    Am I way out of line here Frank ?
    Really appreciate your comments.
    Thanks a lot.
    John

  • How to call Backing Bean method from href tag in JSF. -- URGENT

    Hi guys,
    i am new to JSF. i want one option. how to call a backing bean method from href.
    I searched a lot. i found one component <commandLink>, but i cann't use <commandLink> i have to use only href which is client instructions.
    If anyone knows pls help me. Its Urgent. If u can, give me the code also.
    Suggestions will be appreciated.
    Thanks
    Rajesh

    You can make use of the constructor of the backing bean or the @PostConstruct annotation if you want to use managed properties.
    You may get some ideas out of this: [http://balusc.blogspot.com/2006/06/communication-in-jsf.html].

  • Call a method in VB dll from Java Web Application

    Hi,
    I'm trying to call a method of a VB dll, from a web application developing with J2EE. Is it possible without JNI? And, if it is not possible with a tool, can you help me with an example of JNI using?
    Thank you
    Mary

    maria_eg wrote:
    I'm trying to call a method of a VB dll, from a web application developing with J2EE. Is it possible without JNI? Maybe using Runtime#exec() and rundll32.exe. Depends on the DLL which you want to call.
    And, if it is not possible with a tool, can you help me with an example of JNI using?JNI tutorial: http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jni.html
    JNI forum: http://forum.java.sun.com/forum.jspa?forumID=52

  • Calling multiple DLL from Java and calling same native method

    i have two dll files named DLL_1.dll and DLL_2.dll .
    Both of them contain a native method which has a signature
    JNIEXPORT void JNICALL Java_Database_Notify
    (JNIEnv *, jclass);
    This method is common to both the DLL
    Now i load both of the DLL's using,
    System.loadLibrary("DLL_1");
    System.loadLibrary("DLL_2");
    Both of the DLL are loaded form same Java Application
    But the problem is that , whenever i try to call the Notify Method , it calls the Notify method of DLL_1 only.
    How do i call the Notify Methos of second DLL(i.e DLL_2).
    Is there any reference that i can get to all the DLL files when i load then , so that i can use that reference to invoke the Notify method of that particular DLL.

    i have two dll files named DLL_1.dll and DLL_2.dll .
    Both of them contain a native method which has a
    signature
    JNIEXPORT void JNICALL Java_Database_Notify
    (JNIEnv *, jclass);
    This method is common to both the DLL
    Now i load both of the DLL's using,
    System.loadLibrary("DLL_1");
    System.loadLibrary("DLL_2");
    Both of the DLL are loaded form same Java
    Application
    But the problem is that , whenever i try to call the
    Notify Method , it calls the Notify method of DLL_1
    only.
    How do i call the Notify Methos of second DLL(i.e
    DLL_2).
    Is there any reference that i can get to all the DLL
    files when i load then , so that i can use that
    reference to invoke the Notify method of that
    particular DLL.You need to explain exactly what you are trying to achieve.
    As per the description above it is impossible in java.
    And I didn't say JNI, I said java.
    Your above statement suggests that you think that you can have exactly the same java signature do two different things.
    Note again that I said java not JNI.
    A JNI method is just a tag that represents a java signature. Your description suggests that you are attempting to do it twice.
    There are three possibilities.
    1. Your explanation is incomplete.
    2. You are trying to do something that is impossible in java.
    3. You are trying to solve a problem and your description of your solution is not sufficient to determine what that is (and of course the solution is wrong.)

  • How to call a exe or bat file from java program

    hi,
    i actually want to know that how to call a exe or bat file from program so that i can run them parallely.

    Try this :
    String strCmd = "myFile.bat";
    try
         Runtime rTime = Runtime.getRuntime();
         Process process = rTime.exec(strCmd);
         InputStream p_in = process.getInputStream();
         OutputStream p_out = process.getOutputStream();
         InputStream p_err = process.getErrorStream();
         p_in.close();
         p_out.close();
         p_err.close();
    catch(Exception e) {
         throw new Exception("Unable to start, "+strCmd);
    }

  • Calling existing C/C++ dll from Java Prog

    Hi,
    From within the Java code I want to use the
    functionality of an existing C API. The dll's of C are available. Is it possible to directly call the C Api using Jni or some other technique or do I need to implement a native method in C which would Use the existing C Api to get the values and Pass them to the Java prog.
    Istikhar.

    Is it possible to directly call the C Api using Jni...Depends on what you mean. You can't call it directly from java. You can use JNI, including C/C++ to call it.

  • How to call a procudure (has collection as one of the parameters) from java

    Hi
    I have written a PL/SQL procedure. One of the parameters of the procedure is a collection.
    Could you please tell me how to call this procedure from java.
    Regards

    see the link for example
    http://www.oracle.com/technology/sample_code/tech/java/sqlj_jdbc/files/advanced/sqljSTCollectionSample/SqljSTCollectionSample.sqlj.html

  • How to call dll from Java

    Hi everybody,
    I am trying to call a dll from my java application. Pls tell me how to do it, I seached and found JNI. Is it true
    pls help me and send me some examples
    Thank you and have a nice day

    java_and_me wrote:
    I am trying to call a dll from my java application. Pls tell me how to do it, I seached and found JNI. Is it trueYes, it is true. JNI is the way to go. You'll probably have to write some C code on your own as well, as the DLL is unlikely to be in the format expected by Java already.
    pls help me and send me some examplesOf course. [Here you are|http://www.lmgtfy.com/?q=JNI+tutorial].

Maybe you are looking for

  • Value of the previous cell when I double click a cell in ALV Grid.

    Hi ! Suppose I have an internal table GT_ITAB and I use ALV Grid to print it on the screen. The colums are as below: Invoice No       Invoice Data        Customer No     Amount   90001231        15.01.2009            100024             5 Customer No

  • Using variables in procedures

    hey guys I'm trying to create a procedure to insert data into certain table what i want to do is : 1)get the max(ID) of a certain table so i can increase it by 1 and insert a new record 2)check a condition and depending on that some execution will be

  • Mac os 10.7.5 keyboard problem

    Hi everyone, I have a problem with the keyboard of my macbook pro. Sometimes when I'm working with programs it locks and I can't do nothing but turn it off and reboot. This is a problem I must solve becouse I work whith my mac! I have it since Septem

  • White calendar background on Q10 since update yesterday

    I installed the latest update yesterday. Now, the calendar background color is white and I can't switch to black. Contacts and Phone Apps are still black. White does not only consume more battery but also the contrast with the grey letters is very lo

  • Sales order Release

    Hi, I have the below requirement from my client for make to order, System should allow to run MRP  MD50  only after the sales order is released from authorized person. Kindly suggest required confg.