How to invoke Java method from C++

Hi
My requirement is In C++ we are having three different structures, like
struct one{
int accontno;
char * accountholdername;
long balance;
struct two{
int startdate;
int enddate;
struct three{
char* userid;
char* userpassword;
from c++ how to pass these structures, these structures I have to read in Java class, and in java how receive these structures.
And the sample methods will be like: getCarsData(Input, output, Error);
How do i call the method in JNI, if it is static int method we can call like
getStaticIntMethodID(), instead of int if i have to pass the above mentioned structures how do i do? Should i create an object array in JNI for accessing these three structures?
Suggestions/Samples welcome
Thanks,

Why did you start another thread for this?
I was answering you in the [url http://forum.java.sun.com/thread.jspa?threadID=712137&messageID=4119725#4119725]old thread and you didn't even bother to answer back my (basic) questions.
I told you to use the code tags when pasting code. Got ignored. I also gave you a starting example on how to achieve your goal. Flushed.
Oh well, I'm getting used to it.
Again.
Before starting, allways keep near you the [url http://java.sun.com/j2se/1.5.0/docs/guide/jni/spec/jniTOC.html]JNI reference. All the JNI functions are documented in it.
First you need to create custom Java classes that will match the C++ stucts (remember?).
There is no magic wand in JNI that will transform the C++ structs into the custom Java classes and vice versa.
You'll have to code it by hand, one field at a time. It's a pain.
So for the one, two, three C++ structs (why not posting some real names instead of this crap?),
there will be JOne, JTwo and JThree Java classes.
There is also that other Java class already existing with getCarsData() static method that will fetch the data.
And finally the DLL function wich will call this Java static method, doing the bridge between the C++ structs and the custom Java classes, finally return the data.
Due to the lack of explanation from your posts, I will say that the getCarsData() static method receives a parameter of type JOne
and returns an array of JTwo objects.
So the get_cars_data() DLL function receives a parameter which is a struct one and
returns a pointer to an array of struct two elements.
// C++ structs
struct one {
    int accontno;
    char * accountholdername;
    long balance;
struct two {
    int startdate;
    int enddate;
struct three {
    char * userid;
    char * userpassword;
// custom Java classes
class JOne {
    int accontno;
    String accountholdername;
    int balance;
class JTwo {
    int startdate;
    int enddate;
class JThree {
    String userid;
    String userpassword;
// Java class with static method that gets the data
class DataFetcher {
    static JTwo[] getCarsData(JOne one) {
// DLL function
// struct 'one' parameter is already filled with values.
// Returns an array of 'two' C++ struct obtained from a Java static method
two * get_cars_data(one o) {
    JNIEnv * env;
    /** not show here is the code to either
        create the JVM or
        attach it to the current thread **/
    // get the data from 'one' C++ struct and put it in a new instance of JOne Java class
    jclass oneCls = env->FindClass("JOne");
    jmethodID oneCtorID = env->GetMethodID(oneCls, "<init>", "()V");
    jfieldID accontnoID = env->GetFieldID(oneCls, "accontno", "I");
    jfieldID accountholdernameID = env->GetFieldID(oneCls, "accountholdername", "Ljava/lang/String;");
    jfieldID balanceID = env->GetFieldID(oneCls, "balance", "I");
    jobject oneObj = env->NewObject(oneCls, oneCtorID);
    env->SetIntField(oneObj, accontnoID, o.accontno);
    env->SetObjectField(oneObj, accountholdernameID, env->NewStringUTF((const char *)o.accountholdername));
    env->SetIntField(oneObj, balanceID, o.balanceo);
    // call the Java static method
    jclass dfCls = env->FindClass("DataFetcher");
    jmethodID getCarsDataID = env->GetStaticMethodID(dfCls, "getCarsData", "(LJOne;)[LJTwo;");
    jobjectarray twoArray = (jobjectarray)env->CallStaticObjectMethod(dfCls, getCarsDataID, oneObj);
    // create the 'two' C++ struct array from the Java array of JTwo objects
    jclass twoCls = env->FindClass("JTwo");
    jfieldID startdateID = env->GetFieldID(twoCls, "startdate", "I");
    jfieldID enddateID = env->GetFieldID(twoCls, "enddate", "I");
    jint len = env->GetArrayLength(twoArray);
    two * pt = new two[len];
    for (int i = 0; i < len; i++) {
        jobject twoObj = env->GetObjectArrayElement(twoArray, i);
        pt.startdate = env->GetIntField(twoObj, startdateID);
pt[i].enddate = env->GetIntField(twoObj, enddateID);
// return the resulting 'two' C++ struct array
return pt;
Regards

Similar Messages

  • Invoking java methods from C/C++ on the machine with different JREs

    I implemented Windows NT Service instantiating JVM and invoking several java methods. Everything works but I have an issue with running the service on the machine where multiple different versions of JRE have been installed. The service is calling java methods that require JRE 1.3 or later so I wrote the code that is setting system PATH from within the service based on the configuration stored in the external file. The problem is that the service requires jvm.dll to be in the PATH prior lunching it since this library is instantiated through the implicit linking. When I put jvm.dll in the same path as the service binary I can lunch it but JNI_CreateJavaVM fails and returns -1. This happens even if JRE 1.3 is in the system PATH prior lunching the service.
    Everything works if the system PATH contains references to JRE 1.3 and jvm.dll is removed from the service's directory.
    I am looking for an advice on what is the proper way to deal with invoking java methods from the C/C++ executable in the environment with different versions of JRE.
    Thanks, Kris.

    Here's a way I have done what you are asking about:
    What you want to do is make all of your linking happen at runtime, rather than at compile time. This way, you can edit the PATH variable before the jvm.dll gets loaded.
    Following is some code that I used to handle a dll of my own in this manner. You can decide if you want to write a "wrapper" dll, or if you find it simpler to approach the jvm.dll in this way.
    // Define pointer type for DLL entry point.
         typedef void JREPDLL_API (*EXECUTEREQUEST)(char*, Arguments&);
    // Set up path, load dll, and pass everything off to it.
    HINSTANCE javaServer = javaServer = LoadLibrary("jrepdll.dll");
    if (javaServer != NULL) {
    EXECUTEREQUEST executeRequest = (EXECUTEREQUEST)GetProcAddress(javaServer, "ExecuteRequest");
    if (executeRequest != NULL) {
    if (argc == 1)
         // Execute the request.
         executeRequest("-run", args);
    else
         // Execute the request.
         executeRequest("-console", args);
    Here's some code for how to edit the PATH:
              // Edit the PATH environment variable so that we use our private java.
    char *appendPt;
    char *newPath;
    char *path;
              char tmp[_MAX_PATH];
              // Get the current PATH variable setting.
    path = getenv("PATH");
              // Allocate space for an edited path setting.
              if (path != NULL)
                   newPath = (char*)malloc((_MAX_PATH * 2) + strlen(path));
              else
                   newPath = (char*)malloc((_MAX_PATH * 2));
              // Get upper part of path to desired directories.
              strcpy(tmp, filepath);
              appendPt = strstr(tmp, "dbin\\jreplicator");
              appendPt[0] = '\0';
    sprintf(newPath, "PATH=%sjava\\jre1.2.2\\bin;%sjava\\jre1.2.2\\bin\\classic", tmp, tmp);
    // Append the value of the existing PATH environment variable.
    // If there is anything, append it.
    if (path != NULL) {
         strcat(newPath, ";");
         strncat(newPath, path, (sizeof(newPath) - strlen(newPath) - 2));
    // Set new PATH value.
    _putenv(newPath);
              free(newPath);

  • How to call java method from workflow script?

    Hi
    I have a requirement of updating field value 'Document Status' based on review/approve of content from Workflow and hence need to update the version number. For that I need to call my java method from workflow during submit of review/approve condition. Please let me know how to call java method from workflow?
    Is there any alternative better way to achive this requirement from workflow? Please suggest.
    Thanks,
    Sarang

    OK. So, I think we can all conclude that you don't need to call any Java method, can't we? And, that wfUpdateMetadata is the command that will update your metadata.
    Now, the question is what are its arguments. It has two - the first is the name of a custom metadata field to be updated (let's suppose that one field is called xMinorVersion, and the other xMajorVersion), the other is the new value, e.g. <$wfUpdateMetaData("xMinorVersion", "New value.")$>As for new value - do you insist on using strings? Since you want to increase the value, it would be more convenient to work with numbers. For instance, with integers you could go with <$wfUpdateMetaData("xMinorVersion", xMinorVersion + 1)$>With strings you will need to convert it to numbers and back to strings. Besides, what happens if you have more than 100 minor versions? (you mentioned you want to add 0.01, but that would finally increase the major version, wouldn't it?) So, I think these two numbers are independent (perhaps, with exception that increase on the major version set the minor version to .00).
    If you want to present it, you can use profiles that will construct for you the representation 2.304 out of MajorVersion = 2, MinorVersion = 304
    Solved?

  • How to invoke java application from ABAP

    How to invoke java application from ABAP  ? Suppose I needto execute a EJB wihic is running on my SAP J2EE Enigne from an ABAP Program .
    Thanks,
    Manish

    Hi Manish,
    did you get some further documents concerning "abap program calls ejb"?
    If yes, could you please send me some informations.
    Thank you for your help.
    Kind regards, Patrick.

  • Urgent please ! How to invoke java method with diffrent argument types?

    Hi,
    I am new to JNI.
    I had gone through documentation but it is not of much help.
    Can any one help me out how to invoke the below java method,
    // Java class file
    public class JavaClassFile
    public int myJavaMethod(String[] strArray, MyClass[] myClassArray, long time, int[] ids)
    // implementation of method
    return 0;
    // C++ file with Invokation API and invokes the myJavaMethod Java method
    int main()
    jclass cls_str = env->FindClass("java/lang/String");
    jclass cls_MyClass = env->FindClass("MyClass");
    long myLong = 2332323232;
    int intArray[] = {232, 323, 32, 77 };
    jclass cls_JavaClassFile = env->FindClass("JavaClassFile");
    jmethodID mid_myJavaMethod = env->GetMethodID( cls_JavaClassFile, "myJavaMethod", "([Ljava/lang/String;[LMyClass;J[I)I");
    // invoking the java method
    //jint returnValue = env->CallIntMethod( cls_JavaClassFile, mid_myJavaMethod, stringArray, myClassArray, myLong, intArray ); --- (1)
    //jint returnValue = env->CallIntMethodA( cls_JavaClassFile, mid_myJavaMethod, ...........); --- (2)
    //jint returnValue = env->CallIntMethodV( cls_JavaClassFile, mid_myJavaMethod, ...........); --- (3)
    Can any one tell me what is the correct way of invoking the above Java method of (1), (2) and (3) and how ?
    The statement (1) is compilable but throws error at runtime, why ?
    How can I use statements (2) and (3) over here ?
    Thanks for any sort help.
    warm and best regards.

    You are missing some steps.
    When you invoke a java method from C++, the parameters have to be java parameters, no C++ parameters.
    For example, your code appears to me as thogh it is trying to pass a (C++) array of ints into a java method. No can do.
    You have to construct a java in array and fill it in with values.
    Here's a code snippet:
    jintArray intArray = env->NewIntArray(10); // Ten elments
    There are also jni functions for getting and setting array "regions".
    If you are going to really do this stuff, I suggest a resource:
    essential JNI by Rob Gordon
    There is a chapter devoted to arrays and strings.

  • How to call java method from actionscript

    I've just now started working on Flex. May be its basic question but I’m not aware of it – how can I call a java method from actionscript. I want to call some java method on double click of a event. Can you please let me know how to proceed on this?

    OK. So, I think we can all conclude that you don't need to call any Java method, can't we? And, that wfUpdateMetadata is the command that will update your metadata.
    Now, the question is what are its arguments. It has two - the first is the name of a custom metadata field to be updated (let's suppose that one field is called xMinorVersion, and the other xMajorVersion), the other is the new value, e.g. <$wfUpdateMetaData("xMinorVersion", "New value.")$>As for new value - do you insist on using strings? Since you want to increase the value, it would be more convenient to work with numbers. For instance, with integers you could go with <$wfUpdateMetaData("xMinorVersion", xMinorVersion + 1)$>With strings you will need to convert it to numbers and back to strings. Besides, what happens if you have more than 100 minor versions? (you mentioned you want to add 0.01, but that would finally increase the major version, wouldn't it?) So, I think these two numbers are independent (perhaps, with exception that increase on the major version set the minor version to .00).
    If you want to present it, you can use profiles that will construct for you the representation 2.304 out of MajorVersion = 2, MinorVersion = 304
    Solved?

  • How to call java method from xsl

    hi friends,
    How to call a java method from xsl, i have a xsl file which will call the java method and retrieve the value and display it to the user. but its work well when i set xalan.jar and xerces.jar and the java class files in my classpath and run as
    java org.apache.xalan.xslt.Process -in navigate.xml -xsl nav-exst.xsl -HTML -out navoutpage.html[b]
    in the command prompt but when i deploy it as web application it gives error as
    [b]Namespace 'MyPack' does not contain any functions[b]

    OK. So, I think we can all conclude that you don't need to call any Java method, can't we? And, that wfUpdateMetadata is the command that will update your metadata.
    Now, the question is what are its arguments. It has two - the first is the name of a custom metadata field to be updated (let's suppose that one field is called xMinorVersion, and the other xMajorVersion), the other is the new value, e.g. <$wfUpdateMetaData("xMinorVersion", "New value.")$>As for new value - do you insist on using strings? Since you want to increase the value, it would be more convenient to work with numbers. For instance, with integers you could go with <$wfUpdateMetaData("xMinorVersion", xMinorVersion + 1)$>With strings you will need to convert it to numbers and back to strings. Besides, what happens if you have more than 100 minor versions? (you mentioned you want to add 0.01, but that would finally increase the major version, wouldn't it?) So, I think these two numbers are independent (perhaps, with exception that increase on the major version set the minor version to .00).
    If you want to present it, you can use profiles that will construct for you the representation 2.304 out of MajorVersion = 2, MinorVersion = 304
    Solved?

  • How to invoke Java class from post.POST.jsp

    Hi All,
    I am trying to invoke a simple java method from post.POST.jsp
    I am getting below exception while doing it.
    org.apache.sling.api.scripting.ScriptEvaluationException: org.apache.sling.scripting.jsp.jasper.JasperException: Unable to compile class for JSP:
    An error occurred at line: 32 in the jsp file: /apps/mywebsite/components/customFormAction/post.POST.jsp
    The method test() is undefined for the type DatasourceUtil
    29:          
    30:           ///
    31:          com.day.test.datasource.DatasourceUtil dsUtil = new com.day.test.datasource.DatasourceUtilImpl();
    32:          dsUtil.test();
    33:           //dsUtil.validateLogin(request.getParameter("username"), request.getParameter("password"));
    34:          
    35:           ////
    It appears to resolve the class correctly. I could run the code, if I only comment  dsUtil.test();. As soon as I uncomment, it gives above error.
    In the Utill I have a simple void method which will print a simple text. My package structure is as follows.
    any help will be great
    Tx

    1.  In the interface [1] not the implementation[2] have u defined the method test?
    2.  If it is implemented, Change the bundle version in bnd file and make a new build. Then from felix console verify the latest version reflected in the bundles.
    If 2 works & you are going to make lot of frequent changes then give the version as snapshot till it get stable.
    [1]  com.day.test.datasource.DatasourceUtil
    [2]   com.day.test.datasource.DatasourceUtilImpl

  • How to invoke action method from mail contained link

    Hello,
    my application needs to send mails to users that include links for the user to click on. Something like www.mysite.com/displayData.jsp&id=123. My question is now how I make JSF invoke the respective method in the backed bean to display the data with the id 123 when the user clicks on the link int the mail.
    I wonder whether there is some kind of "catch-all action" that checks whether the user is logged in and authorized whenever any JSP page is invoked. I'm a bit tired of first checking the authorization of some user before processing the remaining part od the backed bean's action method.
    Thanks for any hints,
    Oliver Plohmann

    my application needs to send mails to users that
    include links for the user to click on. Something
    like www.mysite.com/displayData.jsp&id=123. My
    question is now how I make JSF invoke the respective
    method in the backed bean to display the data with
    the id 123 when the user clicks on the link int the
    mail.I dont think there is a way to submit to an action on click of a link. Only possible solution is to invoke the method from the constructor of your Backing Bean and populate the bean fields displayed on your page.
    I wonder whether there is some kind of "catch-all
    action" that checks whether the user is logged in and
    authorized whenever any JSP page is invoked. I'm a
    bit tired of first checking the authorization of some
    user before processing the remaining part od the
    backed bean's action method. You can try out a Servlet filter for doing this.

  • How to call Java method from XSLT??

    Hi All,
    Jdev 11.1.1.3.0
    I have a requirement to implement that, I have to call Java method from XSLT. Could anyone please suggest to implement that??
    Thanks,
    Santosh M E

    As pointed by others, you must expose your method as a custom function, registering with JDeveloper (for development time) as well as with SOA Suite (for runtime).
    In the link below you will find a simple step by step example:
    https://blogs.oracle.com/reynolds/entry/building_your_own_path
    Regards,
    Luis F. Heckler

  • How to call java method from C ?

    Hello,
    I try to call a native method from java which calls java method from the same class. Exception (noSuchMethodError) is thrown. Any ideas?
    Thanx in advance !
    here is the source of the native method :
    JNIEXPORT jint JNICALL Java_TestDll_Proc_1Mul_1Int_1Var_1Var_1Stdcall (JNIEnv * env, jclass jcl, jint jarg1, jint jarg2) {
    int arg1;
    int arg2;
    int arg3;
    jint res;
    char * ch = "test";
    jfieldID fid;
    jmethodID mid;
    int (* procedure) (int *, int * ,int *);
    int mch;
    arg1 = (int )jarg1;
    arg2 = (int )jarg2;
    procedure = GetProcAddress(libraryHandle,"Proc_Mul_Int_Var_Var_Stdcall");
    procedure(&arg1,&arg2,&arg3);
    res = (jint) arg3;
    printf("(*env)->GetMethodID(env, jcl, \"test\", \"()V\");\n");
    mid = (*env)->GetMethodID(env, jcl, "test", "()V");
    printf("(*env)->CallVoidMethod(env, jcl, mid);\n");
    (*env)->CallVoidMethod(env, jcl, mid);
    return res;
    here is the source of the java file:
    public class TestDll {
    static {
    System.loadLibrary("testdllwrap");
    System.out.println("java: Library testdllwrap.dll loaded");
    public TestDll() {
    public native int Proc_Mul_Int_Var_Var_Stdcall(int jarg1, int jarg2);
    public void test() {
    System.out.println("java: test()");
    public static void main(String[] args) {
    TestDll access = new TestDll();
    int a = 5;
    int b = 6;
    int c = 0;
    System.out.println("Calling Proc_Mul_Int_Var_Var_Stdcall");
    c = access.Proc_Mul_Int_Var_Var_Stdcall(a,b);
    System.out.println("Java Result = " + c);

    Something is wrong with the code you posted here.
    Since your native method is not static, it should have the jobject instance as a parameter in the function prototype, not a jclass. Also, you should be calling CallObjectMethod with a jobject, not jclass.
    Check out Jace at http://jace.reyelts.com/jace.
    To call the java method you would do:
    JNIEXPORT jint JNICALL Java_TestDll_Proc_1Mul_1Int_1Var_1Var_1Stdcall
    (JNIEnv * env, jobject jTestDll, jint jarg1, jint jarg2) {
      TestDll testDll( jTestDll );
      testDll.test();
    }God bless,
    -Toby Reyelts

  • How to call java methods from different java file.

    Hi, i create 2 files:
    CircleCalculationMethod.java
    Main.java
    In Main.java, How can i call method in CircleCalculationMethod.java ?
    Should i put everything in same folder ??
    Should i do something like "import CircleCalculationMethod.java"
    Should i do something like create a package
    Thanks
    P/S: i use Eclipse software

    As I suggested in your OTHER threads - the BEST WAY to learn, and often the fastest, is to TRY THINGS yourself.
    Just posting code you get from the internet and asking others to modify it for you won't teach you anything.
    Go through The Java Tutorials. There are trails for ALL of the basic functionality that include working, sample code.
    This is the trail on 'Packages':
    Lesson: Packages (The Java™ Tutorials > Learning the Java Language)
    And this is the one on 'Classes and Objects'. This trail includes sections for methods and how to define and use them.
    Lesson: Classes and Objects (The Java™ Tutorials > Learning the Java Language)

  • Invoking Java Methods from outside ODI

    Is there a good blog on how to do this, I assume a procedure is the best way?

    Bos that makes sense and seems to work, I put this into my text variable:
    SELECT
    CAST(COLLECT(to_char(trade_id)) AS oditmp.t_varchar_tab) AS trade_id
    FROM oditmp.trade_ids
    Validated and returned this when I checked the history :
    Date Value Context
    2011-07-01 08:33:01.0     oracle.sql.ARRAY@294d7bc     DEVELOPMENT
    I assume the values are loaded in here and I can modify my Java Code as below?
    In SQL Developer the same query returns:
    ODITMP.T_VARCHAR_TAB(1,2,3,4,5,6)
    -- Change to Java:
    // Declare variables
    import jar_jcmf;
    trade_ids String;
    String [] str_arr;
    jar_jcmf t = new jar_jcmf();
    int n;
    // Load string array of table values, NOT SURE ABOUT THIS STEP
    trade_ids = #PRJCT.TRADE_IDS;
    // Split String
    str_arr = trade_ids.split(",");
    // Loop over array and execute GetTrade method from JCMF Class
    for (String rec : str_arr) {
    n = Integer.parseInt(rec)
    t.getTrade(n);
    };

  • How to call  Java method from SAPUI5 applications?

    Hi Experts,
        Please give me information that how can I call Java method or jars from SAPUI5 applications?
    Thanks,
    Nag

    Hello Nag,
    why do open this thread in BRM Space? I would suggest reopen this in "UI Development Toolkit for HTML5 Developer Center" Space.
    Regards,
    Tobias

  • Invoke Java method from C++

    hello, I hope you can help me.
    In the moment I am trying to use Global Hotkeys.
    I am able to register global Hotkeys from Java in C++. My problem: I can't invoke an other java method as result of pressing my hotkey.
    void OnHotKey(void *)
         printf("invoke my java method");
    so I want to do a backcall to java in a c++ method. At Beginning Java registers my global Hotkeys in an c++ native method.

    (My JNI is rusty, and the tutorial is gone),
    Something like (Pusdo code, see JNI Spec: Accessing Fields and Methods ):
            JNIEnv * g_env, jobject g_obj;
         void OnHotKey(void *)
              // cut from the example posted above
              jclass cls;
              jmethodID mid;
              cls = (*env)->FindClass(env,"my.Class");
              if( cls == NULL ) {
                        return;
              mid=(*env)->GetMethodID(env, cls, "onHotKey", "()V");
              (*env)->CallVoidMethod( obj, mid );
         CHotkeyHandler hk;
         JNIEXPORT void JNICALL Java_gui_Gui_activateGlobalHotkeys
         (JNIEnv * env, jobject obj) {
              int err, id;
                 hk.RemoveHandler(id = 0);
              hk.InsertHandler(MOD_CONTROL | MOD_ALT, 'A', OnHotKey, id);
              // We need this in OnHotKey
              g_env = env;
              g_obj = obj;
              err = hk.Start("calc.exe");
              if (err != CHotkeyHandler::hkheOk)
                   printf("Error %d on Start()\n", err);
         JNIEXPORT void JNICALL Java_gui_Gui_deactivateGlobalHotkeys
         (JNIEnv * env, jobject obj) {
              int err = hk.Stop();
    }

Maybe you are looking for

  • XML PUBLISHER ERROR :Environment will now switch to UTF-8 code-set.

    Hello , I have developed a new XML Publisher report and when I submit request that is coming as Completed Warning Status and the Log file is given Below. When I consulted My DBA , he told me everything is fine and it is problem either in template fil

  • Lightning-to-30pin adapter compatibility questions

    I'm thinking of upgrading my iPhone 4S to a 5 or 5S.  I own two docks and would like to keep them.  The product description for the adapter states: Supports analogue audio output, USB audio, as well as syncing and charging. One of the docks takes the

  • Email attachment protected view

    Hello, I am running Office 365 Exchange Online and Office 2013 subscriptions on a Windows 7 Pro 64 bit box. Even though protected view is disabled in Word, DOCX email attachments still open in a protected view instead of an edit view.  (see attached

  • A very disturbing Safari 6 problem when downloading files

    After downloading a file from Hubspot.com, this is what I see when clicking on the Show Downloads button on Safari 6. This is actually the third time it's happened. I did a clean install of OS X 10.8 to see if the problem would go away. Sadly, it did

  • Trying to enter a screen name

    I am being asked to enter a screen name somewhere in photoshop touch but every name I answer is met with the message that the name is unavailable. What gives? I've tried about 20 names, all rejected.