Calling a native C Library, from C++ code -

Hi all! please bear with me as i am not sure if my question was specific enough but here goes nothing.
i have a native function that i set up in Java. i use JNI to create my C header file(stub) . all that is good and well but inside my C++ code i want to be able to call a separate C++ function that calls a separate C DLL(library). it seems to me that java shouldn't care about this but evidently it does. i can give you the code and see what you think instead of me trying to explain it all. I am using Linux and g++.
my first idea is that somehow java still needs to know about the C DLL but i dont understand why since i am not calling any functions from the C Library from Java, but rather in my C++ code. please look at the code below. thanks!
//THIS IS THE .java File *********************
public class HelloWorld
public native double getPopulation(double w, double x, double y, double z);
static
   System.loadLibrary("populationLib");
        public static void main(String[] args)
                HelloWorld hello = new HelloWorld();
                double value = hello.getPopulation(-89.3, 30.1, -89.6, 30.8);
                System.out.println("value returned is: " + value);
}now i perform javac HelloWorld.java which creates HelloWorld.class.
now i perform javah -jni HelloWorld which creates my HelloWorld.h C stub.
//THIS IS the HelloWorld.h C Stub*******************
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
#include <shapefil.h>  //*NOTE - i had to add this on my own for the C Library that i want to access
/* Header for class HelloWorld */
#ifndef _Included_HelloWorld
#define _Included_HelloWorld
#ifdef __cplusplus
extern "C" {
#endif
* Class:     HelloWorld
* Method:    getPopulation
* Signature: (DDDD)D
JNIEXPORT jdouble JNICALL Java_HelloWorld_getPopulation
  (JNIEnv *, jobject, jdouble, jdouble, jdouble, jdouble);
double setPopulation(double, double, double, double); //*NOTE - also i had to add this function because it is the separate C++ function that i mentioned at the beginning. this function will try to call the C library functions from shapefil.h.
#ifdef __cplusplus
#endif
#endif
//this is HelloWorld.cpp, my C++ code to match the C Stub that was created earlier***********
#include <iostream>
#include "HelloWorld.h"
using namespace std;
JNIEXPORT double JNICALL Java_HelloWorld_getPopulation(JNIEnv *env, jobject obj, jdouble w, jdouble x,
                                                                                  jdouble y, jdouble z)
  jdouble pop;
  pop = setPopulation(w, x, y, z);
  return (jfloat)pop;
double setPopulation(double x1, double y1, double x2, double y2)
  SHPHandle mySHPhandle = NULL;
  DBFHandle myDBFhandle = NULL;
  SHPObject *mySHPobject = NULL;
  DBFFieldType stuff;
  int field_count;
  int record_count;
  //**NOTE** - these 4 calls below access the functions in the object file that was created through the shapefile C library
  mySHPhandle = SHPOpen("file1.shp", "rb");
  myDBFhandle = DBFOpen("file2.dbf", "rb");
  field_count = DBFGetFieldCount(myDBFhandle);
  record_count = DBFGetRecordCount(myDBFhandle);
  cout << "in set population: x1: " << x1 << " y1: " << y1 << " x2: " << x2 << " y2: " << y2 << endl;
  return 10.0;
}now i need to compile and create the shared library for Java to use:
g++ -shared -I/include files needed -L/library files needed HelloWorld.cpp -o libpopulationLib.so
file successfully created.
now i must run Java against it to see if it runs:
$Java HelloWorld
Exception in thread "main" java.lang.UnsatisfiedLinkError: /home/user/work/iga/src/population/libpopulationLib.so: /home/user/work/iga/src/population/libpopulationLib.so: undefined symbol: SHPOpen
at java.lang.ClassLoader$NativeLibrary.load(Native Method)
at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1751)
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1676)
at java.lang.Runtime.loadLibrary0(Runtime.java:823)
at java.lang.System.loadLibrary(System.java:1030)
at HelloWorld.<clinit>(HelloWorld.java:35)
As you can see it cannot see the function SHPOpen from the external C library i needed to call. I am fairly new to Java and therefore really new to JNI but what surprises me is that Java even cares about or needs to know what i do outside of the original native function that i declared at the beginning.
In any event, what do i need to do to solve this?
thanks so much for your time and patience and help in advance..
Edited by: usmsci on Feb 20, 2008 8:56 AM

Names a mangled in C++.
They are not mangled in C.
You can't mix C and C++ without dealing with that.
I don't see anything in your code that deals with that.

Similar Messages

  • Calling custom COM-based library from Acrobat/Reader javaScript

    Hi All,
    is ist possible to extend the javascript object model? For example, is it possible to call a custom COM-based library from Acrobat/Reader using javaScript. Or is their a diffrent way to call third part libs?
    Thanks
    CommanderPeek

    I need a Reader Integration to a document management system (DMS). The user should interact from Reader GUI with the DMS.
    Nobody is able to give me binding statement, if my customer (this company need plugin for internal use only) will get the Adobe Reader Integration Key License/digital certificate for such a Reader plugin and how high the costs will be. I wait and wait for Adobes’ Feedback :-(
    For this reason I check a different solution with Javascript but I have no idea how to make calls to the DMS from Javascript. On other side are COM- or .Net-based libraries available.

  • Calling a third-party library from JNI-enabled C++ code

    Hi everyone,
    I have some existing C++ application code that extracts data from a file in a special format (HDF5). This code uses a static library (third party) to decode the file format. I would like to wrap this application code in a JNI wrapper so that I can call the code from Java. So I have a situation like this:
    Java front end -> application code (C++) -> static library (C++)
    I have compiled JNI headers and modified the application code accordingly. I created a shared library by bundling the application code together with the static library (using gcc 3.2.2 on Red Hat Linux 9):
    g++ -shared hdf5_jni.cc -o libhdf5_jni.so -I<include path> -L<static library path> -lhdf5
    (the <static library path> contains the static library libhdf5.a). This creates a shared library which contains the application code and the relevant bits of the static library.
    When I call the Java front end, the shared library (libhdf5_jni.so) is correctly found and accessed. However, I get an UnsatisfiedLinkError which I don't understand:
    Exception in thread "main" java.lang.UnsatisfiedLinkError: <blah>/lib/libhdf5_jni.so: <blah>/lib/libhdf5_jni.so: undefined symbol: _Z4formPKcz
    at java.lang.ClassLoader$NativeLibrary.load(Native Method)
    at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1560)
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1485)
    ... etc
    I have no idea what the undefined symbol "_Z4formPKcz" represents. It's not part of the application code or the static library.
    Here's some more info that might help diagnosis:
    1) The problem seems to be due to the approach of having a three-step process (Java code calling bespoke shared library which includes unmodified 3rd-party code). I get an identical error (including the mysterious "_Z4formPKcz" symbol) when trying to do something similar with a different 3rd-party static library.
    2) When I simply have Java code calling C++ code which I have written myself (no calls to static library methods), I have no problems, i.e. there doesn't seem to be a problem with the way I set up the JNI wrappers or the application code, or in the way I create the shared library.
    3) When I simply have C++ code calling the static libraries (i.e. no Java wrapper) I have no problems, i.e. there doesn't seem to be a problem with the application code or the static libraries.
    4) The static libraries were compiled from source using the same compiler that I used to compile the application code.
    5) I'm using J2SDK 1.4.2 on Red Hat Linux 9, although I've tried other versions of the SDK and had the same problem.
    I've done a lot of web searches on the "_Z4formPKcz" symbol and have turned up absolutely nothing (zero Google hits!).
    Any help would be very much appreciated.
    Thanks, Jon

    Thanks chrisswhite,
    I should have mentioned that I tried this too and it didn't solve the problem. You're right though, I should be compiling with -fPIC anyway.
    Jon

  • How to refer to a Class linkage set in Library from external code?

    If one uses [Embed] to refer to external graphic assets its easy to instantiate and use them.
    However, I've got a png in an Fla, with the Class identifier set to "Symbols", Base class is BitmapData.
    I need to instantiate it like this:
    var symbols:BitmapData = new Symbols(1, 1);
    addChild(new Bitmap(symbols));
    Of course the compiler complains about a call to a possibly undefined method Symbols.
    For a temporary fix I guess i'll put the graphic external to the swf, but for this project it needs to be in the library along with everything else.

    If you have a symbol in your library with a Class identity of "Symbols" then you should only need to use...
    var symbols:Symbols = new Symbols();
    addChild(symbols);
    As far as the 1,1 argumets go, are those not something you could assign when the instance is created?

  • Calling a C++ MFC dialog from c code

    Hi,
    I use MFC for the GUI and want to use a dialog class from within the C code. Is that possible? Any comments gratefully appreciated.

    You DLL needs:
    CWinApp(Ex) derived class and also your CDIalog. The easiest way is creating a MFC DLL using the wizard. You need to Create a MFC DLL (statically or dynamically linked like you want - Not a MFC Extension DLL).
    In your  CWinApp class you create a function named i.e. ShowMyDialog. In this function you load the Dialog dynamically using new and you check if the dialog is already existing. Deleting of the diaglg may be done in the destructor.
    Than you need a plain "C" export function. Since the Application class has a global variable  like every MFC project has, you can use this global variable to access the CWinApp::ShowMyDialog.
    At all it is not that difficuilt. If you have further questions feel free to ask.
    Best regards
    Bordon
    Note: Posted code pieces may not have a good programming style and may not perfect. It is also possible that they do not work in all situations. Code pieces are only indended to explain something particualar.

  • Is it possible to link to swc library from c++ code contain actionscript 3

    I m  wittering  actionscript code in c++ file :
    does gcc compiler have flag to link with swc libray
    in other words:
    i have  symbols made by flash and exported as swc library and i want to use it inside c++ actionscript 3 project

    No it does not, but you can build your code as a SWC and link it with the other SWC with mxmlc in console or any flash ide. 

  • Java script callback not called from plugin code

    Hi,
    I am having a plugin which works on FF 3.6. I am trying to make it work on FireFox 4/5. My java script callback for resize is getting called only for first time from plugin code and second time onwards its not getting called. We are using Gecko 2.0 plug-in library.
    I found two bugs in Firefox which may cause call to invalid callback.
    https://bugzilla.mozilla.org/show_bug.cgi?id=664682
    https://bugzilla.mozilla.org/show_bug.cgi?id=653083
    I think because of these two bugs my callback is not getting called. Is there any update for FireFox 4/Firefox5 with the fix for above two issues?
    Thanks,
    Rohit

    The first Bug is listed as a duplicate of the 2nd Bug you posted.
    I don't see any information in the Bug report about which version is going to specifically get the patch. Firefox 4 isn't supported any longer, and I can only assume that with an '''''Importance:''''' of '''normal''', that it won't be "pushed" to Firefox 5. AFAIK, with the new Fast Release schedule only security bugs are going create a situation where a '''''dot#''''' release is going to be made, and other Bugs that have been patched might then be included. With the current release schedule it's going to be 6 weeks between versions, vs the previous 12 to 14 months, or so.
    You may want to try a 6.0 beta to see if it is fixed there.

  • Unable to call a native method

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

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

  • Calling a native library from Java

    Hello,
    I'm trying to call a native method (windows dll) from a web service implemented in Java. I've confirmed that the class I've created to call the native method works when used outside of my web service (ie. in a standard Java application). However, when I try to use the class in the web service, an exception is thrown when
    System.loadLibrary("MyLibrary");
    is executed. The exception thrown is:
    InvocationTargetException
    JAXRPCSERVLET28: Missing port information
    Does any one have any suggestions as to what might be causing this error?
    Thanks

    There are basically 3 steps to calling a native method from your Java code.
    1. Create a C/C++ stub function that will translate between your Java call and the native C method.
    2. Create the dll that exports the stub function.
    3. Invoke the System.loadLibrary("myDllName") method.
    Here's what I did to learn how to use the JNI.
    I first created the class that would be calling the dll:
    public class CallDll
    /** Creates a new instance of CallDll */
    public CallDll()
    static
    //LVtoJava is my dll name.
    System.loadLibrary("LVtoJava");
    //AddDll is the name of the function I'm exporting from my Dll
    //It does not have to be static
    public native static double AddDll(int func, double x, double y);
    I then used the javah utility in the jdk/bin directory to create the C stub header file. Once you have the generated stub header file, you can create an implementation file, and compile it into a dll.
    //My C++ stub, generated by javah utility
    /* DO NOT EDIT THIS FILE - it is machine generated */
    #include <jni.h>
    /* Header for class LabViewDll_CallDll */
    #ifndef IncludedLabViewDll_CallDll
    #define IncludedLabViewDll_CallDll
    #ifdef __cplusplus
    extern "C" {
    #endif
    * Class: LabViewDll_CallDll
    * Method: AddDll
    * Signature: (IDD)D
    JNIEXPORT jdouble JNICALL Java_LabViewDll_CallDll_AddDll
    (JNIEnv *, jclass, jint, jdouble, jdouble);
    #ifdef __cplusplus
    #endif
    #endif
    You may want to note the stub function's signature and how it decorates the function name that you created from your Java class. Do not modify it, as the format is required by the JNI. The javah utility appends the fully qualified package name and the word Java, separated by underscores, to your original function name. You do not need to change the name in your Java class.
    All the other special key words in the function's signature are defined in the jni.h or the jni_md.h (if your using windows).
    You may want to refer to the JNI documention on Sun's website. The book I learned out of is the Core Java Volume 2, published by Sun Microsystems Press. It goes through the details of invoking your first native function and I've found it to be a good reference.
    Hope this helps,
    PS. I seemed to have found the issue with calling my dll from a web service. My dll is actually calling another dll and that seems to be the source of my problems. When I removed the call to the 2nd dll, everything worked fine. So now I need to figure out why the 2nd dll call is an issue.
    Any suggestions?

  • How to call a .bat file from java code?

    How to call a .bat file from java code? and how can i pass parameters to that .bat file?
    Thanks in advance

    thanks for ur reply
    but still i am getting the same error.
    I am trying to run a .bat file of together tool, my code looks like below
    import java.lang.Runtime;
    import java.lang.Process;
    import java.io.File;
    class SysCall{
         public static void main(String args[]){
              String cmd="D://Borland//Together6.2//bin//Together.bat -script:com.togethersoft.modules.qa.QA -metrics out:D://MySamples//Metrics// -fmt:html D://Borland//Together6.2//samples//java//CashSales//CashSales.tpr";
              //String path="D://Borland//Together6.2//bin//Together.bat ";
              Runtime r= Runtime.getRuntime(); //Declare the system call
              try{
                   System.out.println("Before batch is called");
                   Process p=r.exec(cmd);
                   System.out.println(" Exit value =" + p.exitValue());
                   System.out.println("After batch is called");
              /*can produce errors which must be caught*/
              catch(Exception e) {
                   e.printStackTrace();
                   System.out.println (e.toString());
    I am getting the below exception
    Before batch is called
    java.lang.IllegalThreadStateException: process has not exited
    at java.lang.Win32Process.exitValue(Native Method)
    at SysCall.main(SysCall.java:17)
    java.lang.IllegalThreadStateException: process has not exited

  • Calling a PL/SQL from Forte code

    Hi, We are using the Sun UDS 5.1.3
    I need to call directly from the code a PL/SQL stored procedure. It is true that this would defeat the Forte layer purpose but I have a very specific case. Is there an easy way to do so?

    I don't remember how after all these years, but I remember that I made a native Informix call in a special way. So it seems logical that you should be able to do the same for Oracle...
    Scott

  • Why I can't call my native method from my package?

    it is fine if my java code didn't complied into a package.
    But if I complied my java code as a package, and call its native method outside. It give me "UnsatisfiedLinkError". And can not find my method. It is indeed the method is inside.
    Thank a lot any helps. Email me on [email protected]

    I have found that javah does not generate the correct JNI function names when the native function is in a class that is within a Java package. The net result is an Unsatisfied link error.
    The JNI function name must be included in the package name. The naming is a bit complicated and that's why javah should be used, except in this case it does not work. I can't quite remember exactly how it works, something like adding in packagename_1 into the JNI name. The SWIG tool (http://www.swig.org) does generate the correct names when using packages. It is a tool which takes C or C++ header files and generates the JNI and Java classes for you so that you can call C/C++ code from Java. Once you have installed SWIG and run 'make check', have a look in the directory Examples/test-suite/java for the JNI naming for packages. I'll try remember to post the exact naming if you don't want to install SWIG.

  • UnsatisfiedLinkError while calling C library from Java Programm

    Hi,
    I am trying call C function from Java code but I am getting error.
    Below is the code
    package jnitest;
    class HelloWorld {
        private native void print();
        public static void main(String[] args) {
            new HelloWorld().print();
        static {
            System.loadLibrary("HelloWorld");
    }I used following commands to compile and generate header files
    $ javac -d build src/jnitest/HelloWorld.java
    $ javah -d build -classpath build -jni jnitest.HelloWorldThen jnitest_HelloWorld.h was generated and I renamed it to HelloWorld.h.
    I implemented HelloWorld.h in HelloWorld.c.
    Below is the code for both the files
    HelloWorld.h
    /* DO NOT EDIT THIS FILE - it is machine generated */
    #include <jni.h>
    /* Header for class jnitest_HelloWorld */
    #ifndef _Included_jnitest_HelloWorld
    #define _Included_jnitest_HelloWorld
    #ifdef __cplusplus
    extern "C" {
    #endif
    * Class:     jnitest_HelloWorld
    * Method:    print
    * Signature: ()V
    JNIEXPORT void JNICALL Java_jnitest_HelloWorld_print
      (JNIEnv *, jobject);
    #ifdef __cplusplus
    #endif
    #endifHelloWorld.c
    #include <jni.h>
    #include <stdio.h>
    #include "HelloWorld.h"
    JNIEXPORT void JNICALL
    Java_HelloWorld_print(JNIEnv *env, jobject obj)
      printf("Hello World!\n");
      return;
    }I used following commands to generate so file
    gcc -m32 -fPIC -D_REENTRANT -I/opt/jdk1.6.0_19/include -I/opt/jdk1.6.0_19/include/linux -c HelloWorld.c
    gcc -m32 -shared HelloWorld.o -o libHelloWorld.soafter all the execution I get following directory struct in build directory
    $ ls -R
    HelloWorld.c  HelloWorld.h  jnitest  libHelloWorld.so
    ./jnitest:
    HelloWorld.classI am executing following command to run the program.
    build$ java -D. jnitest.HelloWorldbut I am getting exception
    Exception in thread "main" java.lang.UnsatisfiedLinkError: jnitest.HelloWorld.print()V
         at jnitest.HelloWorld.print(Native Method)
         at jnitest.HelloWorld.main(HelloWorld.java:16)I pointed LD_LIBRARY_PATH to build directory and executed
    java -classpath build jnitest.HelloWorldbut I am still getting the same error.
    Please help to fix the issue.
    Thanks,

    The JNI method name in the .h file is different to that in the .c file.

  • How to get exit code from C code when calling java method via JNI?

    Hi, All
    in my project, i need to call a java method from C code using JNI, yet I do
    not know how to
    retrieve the exit code of java program. the java code is like below
    public static void main(....)
    if(error){
    System.exit(-77);// the exit code is -77
    and the JNI c code may like below
    /* Invoke main method. */
        (*env)->CallStaticVoidMethod(env, mainClass, mainID, mainArgs);
    //here I want to retrieve the exit code from java to check if there is an
    error
    any suggestions? thanks

    Hi Liang Zhang,
    In your C code add:
    void (JNICALL y_exit)(jint code) {
    and when you are initialazing JVM options add:
    JavaVMOption options[...];
    options[...].optionString = "exit";
    options[...].extraInfo    = y_exit;
    See http://java.sun.com/j2se/1.3/docs/guide/jni/jni-12.html
    Best regards, Maksim Rashchynski.

  • Calling a javascript function from java code and getting tha value in Java

    Hi,
    I would like to call a Java script function confirmRemove() from Java code upon meeting a condition..
    for example the code snippet is:
    if(true){
    // I want to call js confirmRemove() over here. And get the value of variable "answer" in this if block.
    <html>
    <head>
    <script type="text/javascript">
    function confirmRemove() {
         var answer = confirm("Are you sure you want to Delete?")
    </script>
    </head>
    <body>
    <form>...

    Hi,
    Back in 2003 I have used an Applet which contain java code and this java code was calling the java scripts ( different methods, DHTML etc..)
    There was a component developed by NetScape called JSObject I am not sure it there is other third party component other then the JSObject
    look at this article which shows how (based on JSObject)
    [http://java.sun.com/products/plugin/1.3/docs/jsobject.html|http://java.sun.com/products/plugin/1.3/docs/jsobject.html]
    Regards,
    Alan Meio
    London,UK

Maybe you are looking for