Manipulating C++ Objects in Java Through JNI

Hi,
I have some existing C++ classes objects that I would like to access through Java methods. However, if I use a java method to create an instance of a C++ object, and then I want to edit the state of that C++ object through java, how do I reference the correct C++ object.
For example, if I have a C++ object called Ball, with two variables x and y representing its position and a constructor as well as set methods to set x and y. I then make a java class Ball with the same variables, constructor, and setter methods. But when the java constructor is called, I want the C++ version to be created, and when the java setter methods are called, I want the x and y of the correct C++ Ball instance to change.
Is this is possible, and if so what are the steps needed?
Thank you

See example with C++ structure in
http://www.sharewareplaza.com/Java-Platform-Invoke-API-Demo-version-download_49212.html

Similar Messages

  • Integerating objective c with java through JNI in MAC

    Hi,
    I hv some code in objective c and i hv to call some methods from java code. So i want to use JNI interface for that.
    Could any body give me refrence on how to go about it. I know little bit about integerating c code and java thorugh jni on windows.
    Thanks in advace.
    Regards,
    Prashant

    you need to create dll using vc++ or Borland compiler
    i will try to help you out.
    //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

  • How do I read two dimentional string object in C through JNI

    HI,
    I am new to JNI and Java as well. I want to read two dimentional string object passed by java to a native method written in C/C++. Say for example I have declared a two dimentional string object as below:
    In Java
    class InstanceFieldAccess {
    private String [][] originalAddress = new String[][13];
    private static native String [] accessField(String [][] referenceAddress);
    public static void main(String args[]) {
    /// Java code to get the string object and pass the string object to native method
    new InstanceFieldAccess ().accessField(referenceAddress);
    static {
    System.loadLibrary("ReadStr");
    In C/C++
    I want to read the passed two dimentional string array in C/C++ native code and do the further processing and pass the string
    back to Java class.
    Could anybody tell me how to write the corresponding C/C++ native method.
    Thanks in Advance.
    Pramod.

    i got it thanks.

  • How to access data structures in C dll from java thru JNI?

    We have been given API's( collection of C Functions) from some vendor.
    SDK from vendor consist of:
    Libpga.DLL, Libpga.h,Libpga.lib, Along with that sample program Receiver.h (i don't know its written in C or C++), I guess .C stnads for C files?
    Considering that I don't know C or C++ (Except that I can understand what that program is doing) & i have experience in VB6 and Java, In order to build interface based on this API, I have two option left, Use these dll either from VB or Java.
    As far as I know, calling this DLL in VB requires all the data structures & methods to be declared in VB, I guess which is not the case with Java (? I'm not sure)
    I experiemnted calling these function from Java through JNI, and I successfully did by writting wrapper dll. My question is whether I have to declare all the constants & data structures defined in libpga.h file in java, in order to use them in my java program??
    Any suggesstion would be greatly appreciated,
    Vini

    1. There are generators around that claim to generate suitable wrappers, given some dll input. I suggest you search google. Try JACE, jni, wrapper, generator, .... Also, serach back through this forum, where there have been suggestions made.
    2. In general, you will need to supply wrappers, and if you want to use data from the "C side" in java, then you will need java objects that hold the data.

  • Passing Image data through JNI?

    Hello,
    I am trying find the fastest way to pass image data from Java through JNI. Passing Java images through JNI seems to be a very common thing to do so I expect there's an oft-used approach. Can anyone give me a good explanation of this or point me to some references?
    I need to pass the image data to a C++ function which operates on this data, writing the results to a destination buffer which goes back to Java and gets put back into an image.
    Currently, I'm using BufferedImages and getRGB to get an int array from my source image, passing this through JNI along with another int array to be used as the destination buffer, then calling setRGB with my destination buffer after the JNI function returns. getRGB() preserves the alpha channel of png files, which is functionality I need. The problem with this approach is that getRGB is extremely slow. It can take up to two seconds with a large image on my 1.2 Ghz Athlon. It seems to be performing a copy of the entire source image's data. Maybe there is a way to decode a jpg or png directly into an int array?
    -Aaron Dwyer

    Here's how you could do it for TYPE_4BYTE_ABGR
    BufferedImage img=new BufferedImage(13,10,BufferedImage.TYPE_4BYTE_ABGR);
    img.setRGB(0,0,0xff0000);     
    img.setRGB(5,1,0x00ff00);        
    img.setRGB(1,1,0xcafebabe);
    DataBuffer db=img.getRaster().getDataBuffer();
    int dataType=db.getDataType();
    if (dataType!=DataBuffer.TYPE_BYTE)
         throw new IllegalStateException("I can do it only for TYPE_BYTE");
    int imgType=img.getType();
    if (imgType!=BufferedImage.TYPE_4BYTE_ABGR)
         throw new IllegalStateException("I can do it only for TYPE_4BYTE_ABGR");
    DataBufferByte dbi=(DataBufferByte)db;
    byte[] array=dbi.getData();
    SampleModel model=img.getSampleModel();
    if (!(model instanceof PixelInterleavedSampleModel))
         throw new IllegalStateException("I can do it only for PixelInterleavedSampleModel");
    PixelInterleavedSampleModel pisModel=(PixelInterleavedSampleModel)model;
    if (pisModel.getPixelStride()!=4)
         throw new IllegalStateException("I can do it only for pixel stride of 4");
    if (dbi.getNumBanks()!=1)
         throw new IllegalStateException("I can do it only for 1 band");
    int scanlineBytes=pisModel.getScanlineStride();
    // Access the green Pixel on Position 5,1
    System.out.println( (int)array[5*4 + scanlineBytes] &0xff);     // Alpha        
    System.out.println( (int)array[5*4+1 + scanlineBytes] &0xff);     // Red        
    System.out.println( (int)array[5*4+2 + scanlineBytes] &0xff);     // Green        
    System.out.println( (int)array[5*4+3 + scanlineBytes] &0xff);     // Blue     I've added some checks to make sure we're accessing the data the right way.

  • Executing DLLs from Java using JNI vs Runtime.exec()

    I am trying to understand the best way to execute a dll using java. The dll I am testing with takes a few input parameter. If I use JNI with System.loadLibrary("dll"); what do I need to do to pass the arguements in as well? Can I just add the arguements in the java code like private int xyz = "value"; and expect that the dll will accept them or is there special definitions I have to set up in the dll to make it work?
    Alternatively I was looking at using Runtime to execute the dll by using Runtime.exec("dll param1 param2",env,filePath); Does anyone know if there are drawback to doing it this way vs. using JNI or is this just as efficient? Any help would be appreciated.

    You seem to be confused...
    "execute a dll using java"
    Unless I'm mistaken, a dll is not executable. A dll is a library of code. This code has (hopefully) some well-defined entry points (declared in a header file somewhere) which you must call in a C/C++ file. The arguments you pass to the dll will come from java through JNI.
    As far as your understanding of this entire process, it is obviously confused beyond the scope of a simple reply. I recommend you read the examples and ALL of the documentation available here:
    http://java.sun.com/docs/books/tutorial/native1.1/index.html
    When you get the/an example running (or just set up to run) then post your code and comments here for more help.
    Ian

  • Debugging Java code from c++ through JNI

    I have c++ application calling java methods through JNI. From c++ when I call the java method through JNI how do I debug the java code? It would be of great help if I get to know the settings that I need to do. I am using VC 6.0 for C++ and JBUIlder 8 for JAVA application.OS used is Windows 2000.

    Put
    _asm { int 3 } to C code in the proper place and start your java application. When C code reaches this debug break it shows a dialog to attach the debugger. Attach C debugger and debug Java and C codes.

  • Korean characters, not handled through JNI

    Hello:
    I have a C library that is wrapped through JNI. The data is in Korean, and is returning fine in the C code, but then when I access the data through Java (JString), it is all messed up. Any ideas what is the problem?
    Thanks,
    [email protected]

    Adding on, here is the snippet code, where a command is passed in. The C code executes the command, and returns the result. The UTF and jstring string manipulations are shown below. What is wrong with the assumption if the data itself is of Korean language (double-byte enabled)? Any response would be greatly appreciated. Please respond to this message board, or email at [email protected]
    Thanks,
    Bilal
    JNIEXPORT jshort JNICALL
    Java_execCliCommand(
    JNIEnv *env, jobject obj, jstring cliCmd, jobject cliOutObj)
    jshort jresult;
    P_HANDLE cliOut = (P_HANDLE)NULL;
    char cliOutBuf = (char )NULL;
    jclass jcliOutClass;
    jfieldID joutbufID;
    jstring jcliOutStr;
    * Get the cli command & connectstring and execute the cli.
    const char cliCmdStr = (env)->GetStringUTFChars(env, cliCmd, 0);
    printf("CLI COMMAND : %s\n", (char *)cliCmdStr);
    jresult = cliRunServerCommand((char *)cliCmdStr, &cliOut);
    jcliOutClass = (*env)->GetObjectClass(env, cliOutObj);
    joutbufID = (*env)->GetFieldID(env, jcliOutClass, "outbuf", "Ljava/lang/String;");
    if ( cliOutBuf != NULL ) {
    printf("CLI RESULTS: %s\n", cliOutBuf);
    jcliOutStr = (*env)->NewString(env, (jchar *)cliOutBuf, (jsize)(p_strlen(cliOutBuf)+1));
    printf("UNICODE CLI RESULTS: %s\n", (char *)(*env)->GetStringChars(env, jcliOutStr,0));
    } else {
    jcliOutStr = (*env)->NewStringUTF(env, "Command executed successfully");
    (*env)->SetObjectField(env, cliOutObj, joutbufID, jcliOutStr);
    (*env)->ReleaseStringUTFChars(env, cliCmd, cliCmdStr);
    (*env)->ReleaseStringUTFChars(env, connectString, connectStr);
    return jresult;
    }

  • Casting through JNI

    Hello everyone,
    I'm having myself a little problem. I hava a program in C++ which uses some Java classes through JNI. When i'm invoking a method on a class in Java i get back an object of some type A. But what i need in my C++ program is an object of type B so what i'm looking for is a mechanism to cast my jobject from type A to type B.
    Someone knows how to do this?
    Thanks in advance,
    Bram

    you might want to paste some source code examples in this case.
    you're java objects with be of the base jobject type in JNI/C++ - so you shouldn't need to cast. What method are you using in JNI to invoke?

  • Issues in mapping objects from java to flex - using flex4

    Hi,
    I have a class in java which i want to send to flex4 using BlazeDS as middleware. There are a few issues that i am facing and they are:
    When sending the object across (java to flex), the properties with boolean data type having value as true gets converted to properties with value as  false. Even after setting the value to true it still comes as false on flex side. Can't understand why this is happening.
    When sending the list of object containing property with boolean data type, the object on flex side does not show those properties at all. As of there were no boolean properties in that object.
    Last but not the least, When sending List<ContractFilterVO> contractFilterVOs to flex using remote call, the result typecasted to ArrayCollection does not show the holding objects as ContractFilterVOs but as plain default Object though having all the properties send, except the boolean one mentioned in above points. Basically it is not able to typecast the objects in arraycoolection but the same objects gets typecasted when sent individually.
    In all the above points i am using Remote Service through BlazeDS for connectivity with Java. I have done a lot of this stuff in Flex 3 but doing it for the first time in flex 4, is there anything that Flex 4 needs specific. Below is the pasted code for reference purpose.
    Flex Object
    package com.vo
         [RemoteClass(alias="com.vo.ContractFilterVO")]
    public class ContractFilterVO{
         public function ContractFilterVO(){
         public var contractCode:String;
         public var contractDescription:String;
         public var isIndexation:Boolean;
         public var isAdditional:Boolean;
    * Rmote Part of code
    var remoteObject:RemoteObject = new RemoteObject();
    remoteObject.destination="testService";
    remoteObject.addEventListener(ResultEvent.Result,handleResult);
    public function handleResult(event:ResultEvent):void{
         var contarctFilterVOs:ArrayCollection = event.result as ArrayCollection; //Point 2&3 probelem, if list sent form java
         var contarctFilterVO:ContractFilterVO= event.result as ContractFilterVO; //Point 1 probelem, if only single Object of type ContractFilterVO sent form java
    Java Object
    package com.vo
    public class ContractFilterVO implements Serializable 
         public function ContractFilterVO(){
         private static final long serialVersionUID = 8067201720546217193L;
         private String contractCode;
         private String contractDescription;
         private Boolean isIndexation;
         private Boolean isAdditional;
    I don't understand what is wron in my code on either side, it looks syntactically right. It would be great anyone could help me point out my mistake here. Waiting for right solutions...
    Thanks and Regards,
    Jigar

    Hi Jeffery,
    Thanks for your reply, it did solve my query @ point 3 as well as point 2 where the objects in arraycollection were not geting converted and boolean properties did not appear when list of an objects were received. And hey, i did have public functions for properties defined java class, just forgot to mention here in post, sorry for that.
    The solution you gave was right, but than what if i have a VO which has multiple List of objects coming from Java, than i would have to create an instance of each type of object on flex side this is too tedious, is'nt it? Is there any better solution... out there.
    And jeffery do you some tricks up your sleeve for this Boolean issues to that i am facing in point 1... Still struggling with this one...
    Anyone out there would be more than welcome to point my mistake, if any and provide tips/tricks or solutions...
    Thanks again to Jeffery...
    Waiting for more solutions sooner...
    thanks and Regards,
    Jigar

  • Returning objects from Java stored procedures

    I need to pass an object from Java to a Java SP which updates the object and returns the object back. The Java SP will be calling a PL/SQL procedure which returns some nested tables that I want to stick into the passed object.
    I tried using "IN OUT" for the object in the call spec but got an error that it was not "appropriate for the parameter". So, the next option seems to be to pass it in and then return it from the Java SP. I'm just wondering though what the the best approach for accomplishing this? I've looked through some of the sample code on the OTN but haven't found anything yet that really helps.

    I am trying to use custom object classes. I have setup a type map for the connection and my custom class implements SQLData. Yet, when my client tries to call the Java SP, it gets ORA-00932 complaining of inconsistent data types (expected IN conversion failed).
    I turned on some debug info (i.e. oracle.jdbc.sql=true) but it didn't provide any useful info in regards to why I'm getting this error. Unfortunately, the JDBC Developer's Guide does not provide full examples of the code.

  • Is JMF use hardware accelerated through JNI possible?

    Dear all:
    I try to use JMF decode MPEG-2 data, through VeXP which wrote in C.
    So I think we can call C library through JNI pass encoded MPEG-2 data to VeXP, use hardware decode encoded MPEG-2 data to YUV-format raw data then return it to JAVA.
    but JNI seem can't pass media raw data by call by reference...
    It should cause a lot of memory copy.
    How about it's feasibility?
    Have anyone give me some suggestion?
    Regards,
    white

    There's a few ways to do it, but I'd use a style sheet. So:
    1. Add this to the "creationComplete" Stage event:   sym.$("<link rel='stylesheet' type='text/css' href='styles.css'>").appendTo("#Stage");
    2. Create a style sheet (text file) in your project folder named "styles.css", and define a class:
    .force-webkit-acceleration {
         -webkit-transform: translate3d(0,0,0);
    3. Give your animated element the class "force-webkit-acceleration" in the properties panel (the little c-in-a-box icon next to the title field).
    Be sure that the style sheet file ends up in your "publish/web" folder too.

  • Is it possible in java to pass reference of object in Java?

    Hello,
    I'm relativily new to Java but I have "solid" knowledge in C+ and C# .NET+.
    Is it possible in java to pass reference of object in Java? I read some articles about weakreferences, softreferences, etc. but it seems that it's not what I'm looking for.
    Here is a little piece of code I wrote:
    package Software;
    import java.util.Random;
    * @author Rodrigue
    public class RandomText
        private Random rand = new Random();
        private Thread t;
        private String rText = "Rodrigue";
        public RandomText()
            t = new Thread()
                @Override
                public void run()
                    try
                        while(true)
                            UpdateText();
                            sleep(100);
                    catch(InterruptedException ex)
            t.start();
        private void UpdateText()
            int i = rand.nextInt();
            synchronized (rText)
                rText = String.valueOf(i);
        public String GetText()
            return rText;
    }It's just a class which start a thread. This class updates a text with a random integer 10 times per second.
    I would like to get a reference on the String rText (like in C++ ;) yes I know, I must think in Java :D). So, like that, I could get one time the reference, thanks to the GetText function, and update the text when my application will repaint. Otherwise, I always have to call the GetText method ... which is slow, no?
    Are objects passed by reference in java? Or, my string is duplicated each time?
    Thank you very much in advance!
    Rodrigue

    disturbedRod wrote:
    Ok, "Everything in Java is passed by value. Objects, however, are never passed at all.". Reference of object is passed by value too.
    But, how to solve my problem in Java_? I have an object which is continually modified in a thread. From an another side, this object is continually repainted in a form.I'm not sure I totally understand your problem. If you pass a reference to an object, then both the caller and the method point to the same object. Changing the internal state of the object (e.g. by calling a setter method) through one reference will be observed through both references, since they both point to the same object.
    No, calling a method is not particularly slow. Especially if it's just a simple getter method that returns the value of a member variable.
    If this is happening in a multithreaded context, you'll have to use proper synchronization to ensure that each thread sees the others' changes.

  • To read a DLL from java using JNI

    Hi,
    I had some DLL files (VB 5.0) which are providing interfaces. Is there any chance of accessing that using java (JNI). Also is there any De - Compiler available so that I can get the source code of the DLL file.
    Regards,
    Hari.

    Hola Hari
    To make a dll loadable through JNI, the interface
    inside
    the dll must be implemented the JNI way. Also a COM
    interface does not help.
    I would reccomend a certain product to automatise the
    JNI interfacing process, but that would
    require that you have the sourcecode of the dll
    available.
    But one thing you can do is to write a wrapper that
    contains the dll classes and is implemented the JNI
    way.
    More precisely you write an interface wrapper in c/c++
    that matches the methods of the dll and does use JNI
    methods. Now inside that c++ wrapper you load the dll
    and forward the calls from java to c++ vice versa.
    Download the demo version of CENTRO.java here:
    www.ablon.de
    Bye, nilsHi Nils,
    Thank you for your suggestion. Im new to JNI.
    That dll's are in Visual Basic. I don't have the source code of the dll file. I got the interfaces available in the dll file from a Visual Basic program which make use of the dll file(which we are talking about). As I know only the method signatures in the interfaces(dll file), I request you to kindly provide me some help to wrap it in C/C++ program.
    Thanks in advance.
    Regards,
    Hari.

  • Getting HeapDump on out of memory error when executing method through JNI

    I have a C++ code that executes a method inside the jvm through the JNI.
    I have a memory leak in my java code that results an out of memory error, this exception is caught in my C++ code and as a result the heap dump is not created on the disk.
    I am running the jvm with
    -XX:+HeapDumpOnOutOfMemoryError
    -XX:HeapDumpPath=C:\x.hprof
    Any suggestions?
    Thanks

    I'll rephrase it then.
    I have a java class named PbsExecuter and one static method in it ExecuteCommand.
    I am calling this method through JNI (using CallStaticObjectMethod). sometimes this method causes the jvm to throw OutOfMemoryError and I would like to get a heap dump on the disk when this happens in order to locate my memory leak.
    I've started the jvm with JNI_CreateJavaVM and I've put two options inside the JavaVMInitArgs that is used to create the Jvm. -XX:+HeapDumpOnOutOfMemoryError and -XX:HeapDumpPath=C:\x.hprof
    which supposed to create a heap dump on the disk when OutOfMemoryError occurs.
    Normally if I would execute normal java code, when this exception would occur and I wouldn't catch it the Jvm would crash and the heap dump would be created on the disk.
    Since I need to handle errors in my C++ code I am use ExceptionOccured() and extracts the exception message from the exception it self and write it.
    For some reason when I execute this method through JNI it doesn't create the dump.

Maybe you are looking for

  • Adobe form -- Issue in Displaying Dynamic text along with Static text

    Hi All, I am having an issue when i am displaying a dynamic text along with static text in adobeforms. The dynamic text is slightly coming down and not aligned with the static text. i can see half row it is coming down. how to align both texts to be

  • What modification is needed to AVG virus protection system after updating Firefox?

    When I try to update Firefox on my computer I receive a message that the process will disable my AVG virus protection. I am currently using the latest version of AVG updated earlier this year. I would appreciate further information on what modificati

  • Splitting an iPhoto library?

    I've been using Macs since 2005 and have been taking digital photos for a few years before that (not including prints I've scanned), si I have a rather large iPhoto library - currnetly standing at 81GB. On my 1TB iMac this isn't a problem, but as I h

  • When buying on line my macbook pro will not let me go to the payment page of the web site

    When purchasing goods over the internet my MacBook Pro will not allow me to go beyond the payment page therefore I am unable to complete my purchase. If I use a Windows operated PC in the same household I do not have this problem. Are there any secur

  • Howler of a "Gotcha" in Photoshop menu creation

    This is more a warning than a bug report - as I am not at all sure it is really a bug. When designing menus for DVD in Photoshop, it is absolutely imperative to use the correct resolution & image size because of the following issue that just bit me i