Converting jstring to const char * using JNI

Hi Folks,
Almost complete with the registry access dll and passing to java. My last question is how do I convert a jstring in a const char * ? There may be a method of the JNIEnv that I can use. Can anyone assist? Thanks.

Look at the JNI GetString functions.

Similar Messages

  • Converting jstring to char in c

    I'm trying to convert a jstring to const char (a pointer), but I keep getting an exception.
    is there some kind of defenition I'm missing????
    here's part of the code:
    jmethodID methID;
    jstring jstr;
    const char *str;
    /* Get a reference to obj2 class */
    jclass cls = (*env)->GetObjectClass (env, obj2);
    if (cls == NULL){
    return; /*return in case the object couldn't be found */
    methID = (*env)->GetMethodID (env, cls, "getPgmId", "()Ljava/lang/String;");
    jstr = (jstring) (*env) -> CallCharMethod(env, obj2, methID);
    if (jstr == NULL){
    printf (" \nthe result String is null \n");
    fflush(stdout);
    return;
    str = (char)(*env)->GetStringUTFChars (env, jstr, 0);

    your method signature shows that your method returns a string but you are using "CallCharMethod"...you should be using CallObjectMethod since a string in java is actually an object not a datatype.
    this is an example of getting a jstring and converting it to a char*. i need the char* so i do a strdup and release...
    jstring desc = (jstring)env->CallObjectMethod(obj, mid, failType);
    if(desc == NULL){
         cout << "desc == null" << endl;
         return (char*)errorHandler('c', JNI_NO_METHOD);
    char* cDesc = strdup(env->GetStringUTFChars(desc, 0));
    env->ReleaseStringUTFChars(desc, cDesc);

  • Converting "jstring" to "char *" in VC++

    Hello,
    I have a native method whose input parameter is a string. I used the below lines of code to get a char *. These code i got it from the JAVA TUTORIALS only.
    JNIEXPORT jint JNICALL Java_SpringDLL_createExtensionSpringDXF
    (JNIEnv *env, jobject obj, jstring jsprData)
    const char sprData = (env)->GetStringUTFChars(env, jsprData, 0);
    printf("%s", sprData );
    (*env)->ReleaseStringUTFChars(env, jsprData, sprData);
    I am using VC++ Application Wizard to generate the DLL.
    The error i am getting is :
    SpringDLL.cpp(72) : error C2819: type 'JNIEnv_' does not have an overloaded member 'operator ->'
    C:\JDK1.3\INCLUDE\jni.h(746) : see declaration of 'JNIEnv_'
    SpringDLL.cpp(72) : error C2227: left of '->GetStringUTFChars' must point to class/struct/union
    SpringDLL.cpp(100) : error C2819: type 'JNIEnv_' does not have an overloaded member 'operator ->'
    C:\JDK1.3\INCLUDE\jni.h(746) : see declaration of 'JNIEnv_'
    SpringDLL.cpp(100) : error C2227: left of '->ReleaseStringUTFChars' must point to class/struct/union
    Can anybody help me out how to get rid of this error. Please its an very urgent....
    if you can send me an email then please don't hesitate to send it to "[email protected]".
    Thanks,
    Patro

    The code from the tutorials id for C not C++. As you are using C++, use 'env' like this
        jclass     cls=env->GetObjectClass(obj);because when using C++ env is a pointer to an object.

  • Jni: converting char* to JNI type?

    In my native C++ code I have to call a function through another dll. This function has an OUT parameter which is of type: char *.
    I need to return this parameter to the calling Java method through the native C++ code using JNI ...is the corresponding JNI type that i should be returning jcharArray or jstring??
    If so, how do I convert char * to the jcharArray/jstring type.

    Things may not be that simple. Beware that this function dos not expect any kind of char* . It expects UTF-8-encoded string.
    it means that if your C string is all basic (i.e <127) chars, it is ok.
    but if you have some special characters ( where ascii code > 128), it may not be interpreted the way you want.
    see the end of http://java.sun.com/j2se/1.3/docs/guide/jni/spec/types.doc.html
    for more details.

  • Converting jstring to char*

    Hi,
    I would like to convert a jstring (which is an argument in a method) to a C++ char*. How to do that?
    I think it should be something like:
    JNIEXPORT void JNICALL
    Java_HelloWorld_displayHelloWorld(JNIEnv* env, jobject obj, jstring str)
    char* text= ???;
    Thank you for your answer :-)

    const char * stringa = env->GetStringUTFChars(_jstringa,null);

  • Call to a C++ DLL, using JNI - C++ method has char*

    I am trying to link into an existing C++ Dynamically Linked Library(DLL) using the Java Native Interface(JNI).
    All goes fine, and the library loads into the current program, however when I try to call the function, it crashes. The function has char pointers, and I haven;t been able to get Java to simulate them. Is there a way?????
    I have tried using and array of chars .....char[], and String, but no dice.
    Any suggestions O'learned Java ones??

    It will be necessary for you to write a JNI adapter in C/C++ to accomplish this. Java character strings and arrays are very different from those of C/C++ and you'll have to use JNI functions to adapt.
    Chuck

  • JVM Crash When Using JNI and COM

    I'm trying to call a DLL compiled from VB6 source code that I do not have access to. The VB6 code simply retrieves data from a DB2 database using ADO and my client code grabs that data and marshals it to my Java code. I'm attempting to achieve this using JNI and COM (without a third-party bridge). It works 75% of the time, but the other 25% of the time, the JVM crashes with the usual Hotspot crash log containing an access violation exception. However, I don't know what in my C++ code (VC++ 8) could be causing this except for passing a "wild" pointer to the code lying underneath the COM object interface. If that is the case, I don't know how I am doing that.
    The Java code that is calling my native method is running on Tomcat 5.5.25 and just to be safe, I am not allowing multiple threads to concurrently call the method in my JNI DLL (though I realize that this will kill performance). Once I can get past this problem, I'll do the COM interfacing on a worker thread in my native code so I don't screw up CoInitialize and CoUninitialize calls in the case the same thread is concurrently executing multiple calls to my native code.
    I've noticed that in most cases, the JVM crashes during my call to the pClsAccount->OpenConnection method. However, my DLL isn't what is listed on the top of the call stack, which is why I suspect the passing of a wild pointer, though I'm just taking a guess at that. Does anyone have an idea as to what's going on ?
    JNIEXPORT jobject JNICALL Java_CustomerInfo_nGetCustomerAccountInfo(JNIEnv *env, jobject customerInfo, jstring accountNumber, jstring iniFileName)
    jboolean isCopy;
    // Account info class and instance to be instantiated
    jclass accountInfoCls = NULL;
    jobject accountInfoObj = NULL;
    // The constructor ID of the accountInfoCls
    jmethodID ctorID = NULL;
    // Pointer to the interface for the ClsAccount COM object
    _clsAccount *pClsAccount = NULL;
    HRESULT hr;
    BSTR bstrIniFileName(L"");
    try
    const char *nativeAccountNumber = NULL;
    if (accountNumber != NULL)
    nativeAccountNumber = env->GetStringUTFChars(accountNumber, &isCopy);
    else
    jclass newExcCls;
    env->ExceptionDescribe();
    env->ExceptionClear();
    newExcCls = env->FindClass("java/lang/IllegalArgumentException");
    env->ThrowNew(newExcCls, "accountNumber passed in was null !");
    return NULL;
    // Initialization
    variantt varConnectionSucceeded = variantt(false);
    variantt varGetAccountInfoSucceeded = variantt(false);
    variantt varAccountNumber = variantt(nativeAccountNumber);
    bstrt bstrLastPaymentDate = bstrt();
    bstrt bstrLastErrorMessage = bstrt();
    bstrt bstrLastErrorNumber = bstrt();
    jlong jTotalDue = NULL;
    jlong jEstablishedDueDay = NULL;
    jlong jLastPaymentAmount = NULL;
    jstring jLastPaymentDate = NULL;
    jstring jLastErrorMessage = NULL;
    jstring jLastErrorNumber = NULL;
    jthrowable jException = NULL;
    const char *chLastPaymentDate = NULL;
    const char *chLastErrorMessage = NULL;
    const char *chLastErrorNumber = NULL;
    long long totalDue;
    long long lastPaymentAmount;
    long establishedDueDateDay;
    //Convert string from Java string to C string to VB string
    const char *nativeIniFileName = NULL;
    if (iniFileName != NULL)
    nativeIniFileName = env->GetStringUTFChars(iniFileName, &isCopy);
    else
    jclass newExcCls;
    env->ExceptionDescribe();
    env->ExceptionClear();
    newExcCls = env->FindClass("java/lang/IllegalArgumentException");
    env->ThrowNew(newExcCls, "iniFileName passed in was null");
    return NULL;
    bstrIniFileName = comutil::ConvertStringToBSTR(nativeIniFileName);
    CoInitialize(NULL);
    // Create an instance of the COClass with the interface over it
    hr = CoCreateInstance(__uuidof(clsAccount), NULL, CLSCTX_INPROC_SERVER, __uuidof(_clsAccount), (void **)&pClsAccount);
    if (hr == S_OK)
    varConnectionSucceeded.boolVal = pClsAccount->OpenConnection(&bstrIniFileName);
    &#12288;
    if (varConnectionSucceeded.boolVal == -1)
    varGetAccountInfoSucceeded.boolVal = pClsAccount->GetAccountPaymentInformation(&(varAccountNumber.GetVARIANT()));
    env->ReleaseStringUTFChars(accountNumber, nativeAccountNumber);
    // Extract all available account information from the ClsAccount object
    if (varGetAccountInfoSucceeded.boolVal == -1)
    totalDue = pClsAccount->TotalDue.int64;
    establishedDueDateDay = pClsAccount->EstablishedDueDateDay;
    lastPaymentAmount = pClsAccount->LastPaymentAmount.int64;
    bstrLastPaymentDate = pClsAccount->LastPaymentDate;
    chLastPaymentDate = comutil::ConvertBSTRToString(bstrLastPaymentDate.GetBSTR());
    jTotalDue = (jlong)totalDue;
    jEstablishedDueDay = (jlong)establishedDueDateDay;
    jLastPaymentAmount = (jlong)lastPaymentAmount;
    jLastPaymentDate = env->NewStringUTF(chLastPaymentDate);
    delete[] chLastPaymentDate;
    pClsAccount->CloseConnection();
    // Populate error fields if any errors occur
    bstrLastErrorMessage = pClsAccount->LastErrMessage;
    chLastErrorMessage = comutil::ConvertBSTRToString(bstrLastErrorMessage.GetBSTR());
    bstrLastErrorNumber = pClsAccount->LastErrNumber;
    chLastErrorNumber = comutil::ConvertBSTRToString(bstrLastErrorNumber.GetBSTR());
    jLastErrorMessage = env->NewStringUTF(chLastErrorMessage);
    jLastErrorNumber = env->NewStringUTF(chLastErrorNumber);
    delete[] chLastErrorMessage;
    delete[] chLastErrorNumber;
    const char* clsName = "com/nuance/merchantsmutual/businessentities/CustomerAccountInfo";
    // Find the Java class and the ID of its constructor
    accountInfoCls = env->FindClass(clsName);
    ctorID = env->GetMethodID(accountInfoCls, "<init>", "(JJJLjava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
    jException = env->ExceptionOccurred();
    if (jException != NULL)
    env->ExceptionDescribe();
    env->ExceptionClear();
    //Release all resources associated with the ClsAccount instance
    pClsAccount->Release();
    //Instantiate the class with the given parameters
    accountInfoObj = env->NewObject(accountInfoCls, ctorID, jTotalDue, jEstablishedDueDay, jLastPaymentAmount, jLastPaymentDate, jLastErrorMessage, jLastErrorNumber);
    jException = env->ExceptionOccurred();
    if (jException != NULL)
    env->ExceptionDescribe();
    env->ExceptionClear();
    else if (hr == REGDB_E_CLASSNOTREG)
    cout << "COM class not registered" << endl;
    else if ( hr == CLASS_E_NOAGGREGATION)
    cout << "COM class can't be aggregated" << endl;
    else if (hr == E_NOINTERFACE)
    cout << "No interface for COM class clsAccount" << endl;
    else if (hr == E_POINTER)
    cout << "*ppv pointer was NULL !" << endl;
    else
    cout << "Error occurred while creating COM object. HR is [" << hr << "]" << endl;
    // Free the BSTR because a new one was returned with a call to comutil::ConvertStringToBSTR
    SysFreeString(bstrIniFileName);
    // Release the string when it's no longer needed. MUST call if string won't be used
    // anymore or else a memory leak will occur
    env->ReleaseStringUTFChars(iniFileName, nativeIniFileName);
    CoUninitialize();
    &#12288;
    catch (_com_error &e)
    cout << "Encountered an exception in GetCustomerAccountInfo: Error was " << e.ErrorMessage();
    pClsAccount->Release();
    catch (...)
    pClsAccount->Release();
    return accountInfoObj;
    Edited by: Cthulhu76 on Jan 5, 2010 9:18 AM

    0x49202400 JavaThread "ContainerBackgroundProcessor[StandardEngine[Catalina]]" daemon [_thread_blocked, id=5340, stack(0x49bf0000,0x49c40000)]
    0x48a7e800 JavaThread "Thread-1" [_thread_in_native, id=5976, stack(0x48f00000,0x48f50000)]
    0x48a0dc00 JavaThread "Low Memory Detector" daemon [_thread_blocked, id=3072, stack(0x48c60000,0x48cb0000)]
    0x48a09000 JavaThread "CompilerThread0" daemon [_thread_blocked, id=4988, stack(0x48c10000,0x48c60000)]
    0x48a07c00 JavaThread "Attach Listener" daemon [_thread_blocked, id=3124, stack(0x48bc0000,0x48c10000)]
    0x48a07000 JavaThread "Signal Dispatcher" daemon [_thread_blocked, id=2572, stack(0x48b70000,0x48bc0000)]
    0x489f5c00 JavaThread "Finalizer" daemon [_thread_blocked, id=5752, stack(0x48b20000,0x48b70000)]
    0x489f4c00 JavaThread "Reference Handler" daemon [_thread_blocked, id=2596, stack(0x48ad0000,0x48b20000)]
    0x003c6000 JavaThread "main" [_thread_in_native, id=4252, stack(0x00820000,0x00870000)]
    Other Threads:
    0x489f0400 VMThread [stack: 0x48a80000,0x48ad0000] [id=5624]
    0x48a18800 WatcherThread [stack: 0x48cb0000,0x48d00000] [id=1192]
    VM state:not at safepoint (normal execution)
    VM Mutex/Monitor currently owned by a thread: None
    Heap
    def new generation total 36288K, used 12762K [0x02940000, 0x050a0000, 0x07800000)
    eden space 32256K, 34% used [0x02940000, 0x0343af58, 0x048c0000)
    from space 4032K, 37% used [0x04cb0000, 0x04e2ba28, 0x050a0000)
    to space 4032K, 0% used [0x048c0000, 0x048c0000, 0x04cb0000)
    tenured generation total 483968K, used 7518K [0x07800000, 0x250a0000, 0x42940000)
    the space 483968K, 1% used [0x07800000, 0x07f57958, 0x07f57a00, 0x250a0000)
    compacting perm gen total 14080K, used 14016K [0x42940000, 0x43700000, 0x46940000)
    the space 14080K, 99% used [0x42940000, 0x436f0320, 0x436f0400, 0x43700000)
    No shared spaces configured.
    Dynamic libraries:
    0x00400000 - 0x0040f000      C:\Program Files\Apache Software Foundation\Tomcat 5.5\bin\tomcat5.exe
    0x7c800000 - 0x7c8c0000      C:\WINDOWS\system32\ntdll.dll
    0x77e40000 - 0x77f42000      C:\WINDOWS\system32\kernel32.dll
    0x77380000 - 0x77411000      C:\WINDOWS\system32\USER32.dll
    0x77c00000 - 0x77c48000      C:\WINDOWS\system32\GDI32.dll
    0x77f50000 - 0x77feb000      C:\WINDOWS\system32\ADVAPI32.dll
    0x77c50000 - 0x77cef000      C:\WINDOWS\system32\RPCRT4.dll
    0x76f50000 - 0x76f63000      C:\WINDOWS\system32\Secur32.dll
    0x77ba0000 - 0x77bfa000      C:\WINDOWS\system32\MSVCRT.dll
    0x7c8d0000 - 0x7d0cf000      C:\WINDOWS\system32\SHELL32.dll
    0x77da0000 - 0x77df2000      C:\WINDOWS\system32\SHLWAPI.dll
    0x76290000 - 0x762ad000      C:\WINDOWS\system32\IMM32.DLL
    0x77420000 - 0x77523000      C:\WINDOWS\WinSxS\x86_Microsoft.Windows.Common-Controls_6595b64144ccf1df_6.0.3790.3959_x-ww_D8713E55\comctl32.dll
    0x6d7c0000 - 0x6da10000      C:\Program Files\Java\jre1.6.0_07\bin\client\jvm.dll
    0x76aa0000 - 0x76acd000      C:\WINDOWS\system32\WINMM.dll
    0x7c340000 - 0x7c396000      C:\WINDOWS\system32\MSVCR71.dll
    0x6d270000 - 0x6d278000      C:\Program Files\Java\jre1.6.0_07\bin\hpi.dll
    0x76b70000 - 0x76b7b000      C:\WINDOWS\system32\PSAPI.DLL
    0x6d770000 - 0x6d77c000      C:\Program Files\Java\jre1.6.0_07\bin\verify.dll
    0x6d310000 - 0x6d32f000      C:\Program Files\Java\jre1.6.0_07\bin\java.dll
    0x6d7b0000 - 0x6d7bf000      C:\Program Files\Java\jre1.6.0_07\bin\zip.dll
    0x6d570000 - 0x6d583000      C:\Program Files\Java\jre1.6.0_07\bin\net.dll
    0x71c00000 - 0x71c17000      C:\WINDOWS\system32\WS2_32.dll
    0x71bf0000 - 0x71bf8000      C:\WINDOWS\system32\WS2HELP.dll
    0x71b20000 - 0x71b61000      C:\WINDOWS\system32\mswsock.dll
    0x5f270000 - 0x5f2ca000      C:\WINDOWS\system32\hnetcfg.dll
    0x71ae0000 - 0x71ae8000      C:\WINDOWS\System32\wshtcpip.dll
    0x76ed0000 - 0x76efa000      C:\WINDOWS\system32\DNSAPI.dll
    0x76f70000 - 0x76f77000      C:\WINDOWS\System32\winrnr.dll
    0x76f10000 - 0x76f3e000      C:\WINDOWS\system32\WLDAP32.dll
    0x76f80000 - 0x76f85000      C:\WINDOWS\system32\rasadhlp.dll
    0x4a6a0000 - 0x4a6ac000      C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\MMI\WEB-INF\lib\CustomerInfoProxy.dll
    0x77670000 - 0x777a9000      C:\WINDOWS\system32\ole32.dll
    0x77d00000 - 0x77d8b000      C:\WINDOWS\system32\OLEAUT32.dll
    0x7c420000 - 0x7c4a7000      C:\WINDOWS\WinSxS\x86_Microsoft.VC80.CRT_1fc8b3b9a1e18e3b_8.0.50727.4053_x-ww_E6967989\MSVCP80.dll
    0x78130000 - 0x781cb000      C:\WINDOWS\WinSxS\x86_Microsoft.VC80.CRT_1fc8b3b9a1e18e3b_8.0.50727.4053_x-ww_E6967989\MSVCR80.dll
    0x777b0000 - 0x77833000      C:\WINDOWS\system32\CLBCatQ.DLL
    0x77010000 - 0x770d6000      C:\WINDOWS\system32\COMRes.dll
    0x77b90000 - 0x77b98000      C:\WINDOWS\system32\VERSION.dll
    0x75da0000 - 0x75e5d000      C:\WINDOWS\system32\SXS.DLL
    0x75e60000 - 0x75e87000      C:\WINDOWS\system32\apphelp.dll
    0x4dc30000 - 0x4dc5e000      C:\WINDOWS\system32\msctfime.ime
    0x4b0d0000 - 0x4b395000      C:\WINDOWS\system32\xpsp2res.dll
    0x71bb0000 - 0x71bb9000      C:\WINDOWS\system32\WSOCK32.dll
    0x4bbe0000 - 0x4bbea000      C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\MMI\WEB-INF\lib\ClearTranProxy.dll
    0x745e0000 - 0x7489e000      C:\WINDOWS\system32\msi.dll
    0x71c40000 - 0x71c97000      C:\WINDOWS\system32\NETAPI32.dll
    0x4bc50000 - 0x4bc6c000      C:\WINDOWS\system32\DBNETLIB.DLL
    0x71f60000 - 0x71f64000      C:\WINDOWS\system32\security.dll
    0x76c90000 - 0x76cb7000      C:\WINDOWS\system32\msv1_0.dll
    0x76cf0000 - 0x76d0a000      C:\WINDOWS\system32\iphlpapi.dll
    0x761b0000 - 0x76243000      C:\WINDOWS\system32\crypt32.dll
    0x76190000 - 0x761a2000      C:\WINDOWS\system32\MSASN1.dll
    0x4bcf0000 - 0x4bcff000      C:\Program Files\Common Files\System\Ole DB\SQLOLEDB.RLL
    0x4a8a0000 - 0x4a8aa000      C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\MMI\WEB-INF\lib\MIGI.DLL
    0x73570000 - 0x736c2000      C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\MMI\WEB-INF\lib\MSVBVM60.DLL
    0x4a950000 - 0x4a9e2000      C:\Program Files\Common Files\System\ado\msado15.dll
    0x74a50000 - 0x74a6a000      C:\WINDOWS\system32\MSDART.DLL
    0x4c850000 - 0x4c8c9000      C:\Program Files\Common Files\System\Ole DB\oledb32.dll
    0x4dbb0000 - 0x4dbc1000      C:\Program Files\Common Files\System\Ole DB\OLEDB32R.DLL
    VM Arguments:
    jvm_args: -Dcatalina.home=C:\Program Files\Apache Software Foundation\Tomcat 5.5 -Dcatalina.base=C:\Program Files\Apache Software Foundation\Tomcat 5.5 -Djava.endorsed.dirs=C:\Program Files\Apache Software Foundation\Tomcat 5.5\common\endorsed -Djava.io.tmpdir=C:\Program Files\Apache Software Foundation\Tomcat 5.5\temp -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.util.logging.config.file=C:\Program Files\Apache Software Foundation\Tomcat 5.5\conf\logging.properties -Djava.library.path=C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\MMI\WEB-INF\lib vfprintf -Xms512m -Xmx1024m
    java_command: <unknown>
    Launcher Type: generic
    Environment Variables:
    JAVA_HOME=C:\Program Files\Java\jdk1.6.0_07
    [error occurred during error reporting (printing environment variables), id 0xc0000005]
    --------------- S Y S T E M ---------------
    OS: Windows Server 2003 family Build 3790 Service Pack 2
    CPU:total 4 (4 cores per cpu, 1 threads per core) family 6 model 7 stepping 6, cmov, cx8, fxsr, mmx, sse, sse2, sse3, ssse3
    Memory: 4k page, physical 2097151k(2097151k free), swap 4194303k(4194303k free)
    vm_info: Java HotSpot(TM) Client VM (10.0-b23) for windows-x86 JRE (1.6.0_07-b06), built on Jun 10 2008 01:14:11 by "java_re" with MS VC++ 7.1
    time: Mon Dec 28 15:24:00 2009
    elapsed time: 600 seconds

  • Convert from jchar to char

    Does any one know how to convert from jchar to char?
    Thank you,

    does it have to be a jchar or can you get a jstring? is it possible to convert your jchar into a jstring before you pick it up in jni? if you can get a jstring you can use the function
    const char* GetStringUTFChars(jstring str, jboolean *isCopy)
    you would get back a character pointer that points to a single char plus the null terminator

  • How can i convert jstring to PSTR with chinese character

    Hi all,
    I'm not an expert of C++. So please help me to fix the following problem.
    I'm using jni to call the dll. In java side, the input parameter is jstring. In C++ side, the input parameter of PrintDrugReceipt are PSTR.
    The following is the code of my C++:
    #include <windows.h>
    #include <stdio.h>
    #include <jni.h>
    #include "DrugReceiptWrapper.h"
    #include "DrugReceipt.h"
    const char * JNU_GetStringNativeChars(JNIEnv *env, jobject obj, jstring jstr) {
    jbyteArray bytes = 0;
    jthrowable exc;
         jclass cls;
         jmethodID getBytes;
    char *result = 0;
    if ((*env)->EnsureLocalCapacity(env, 2) < 0) {
    return 0; /* out of memory error */
         cls = (*env)->GetObjectClass(env, obj);
         getBytes = (*env)->GetMethodID(env, cls, "getBytes","()[B");
         //jbyteArray buf = (jbyteArray*)(*env)->CallObjectMethod(env, obj, jlprSourceChiName, getBytes);
         bytes = (*env)->CallObjectMethod(env, jstr, getBytes);
         exc = (*env)->ExceptionOccurred(env);
         if (!exc) {
             jint len = (*env)->GetArrayLength(env, bytes);
             result = (char *)malloc(len + 1);
             if (result == 0) {
                 //JNU_ThrowByName(env, "java/lang/OutOfMemoryError", 0);
                 (*env)->DeleteLocalRef(env, bytes);
                 return 0;
    (*env)->GetByteArrayRegion(env, bytes, 0, len, (jbyte *)result);
    result[len] = 0; /* NULL-terminate */
    } else {
    (*env)->DeleteLocalRef(env, exc);
    (*env)->DeleteLocalRef(env, bytes);
    return result;
    JNIEXPORT jlong JNICALL
    Java_TestPrint_PrintDrugReceiptWrapper(
    JNIEnv *env, jobject obj,
    jstring jlprPrinterPort, jstring jlprSourceChiName,
    jstring jlprTargetChiName, jstring jlprPrintData1,
    jstring jlprPrintData2, jstring jlprCaseNo, jstring jlprReceiptNo){
         PSTR lprPrinterPort;
         PSTR lprSourceChiName;
         PSTR lprTargetChiName, lprPrintData1;
    PSTR lprPrintData2 , lprCaseNo, lprReceiptNo;
         printf("before %s", jlprSourceChiName);
         lprPrinterPort = (*env)->GetStringChars(env, jlprPrinterPort , 0);
         lprSourceChiName = (*env)->GetStringChars(env, jlprSourceChiName, 0);     
         lprTargetChiName = (*env)->GetStringChars(env, jlprTargetChiName, 0);
         lprPrintData1 = (*env)->GetStringChars(env, jlprPrintData1 , 0);
         lprPrintData2 = (*env)->GetStringChars(env, jlprPrintData2 , 0);
    lprCaseNo = (*env)->GetStringChars(env, jlprCaseNo , 0);
         lprReceiptNo = (*env)->GetStringChars(env, jlprReceiptNo , 0);
         PrintDrugReceipt(lprPrinterPort, lprSourceChiName, lprTargetChiName, lprPrintData1, lprPrintData2, lprCaseNo, lprReceiptNo);
         (*env)->ReleaseStringChars(env, jlprPrinterPort , lprPrinterPort);
         (*env)->ReleaseStringChars(env, jlprSourceChiName, lprSourceChiName);
         (*env)->ReleaseStringChars(env, jlprTargetChiName, lprTargetChiName);
         (*env)->ReleaseStringChars(env, jlprPrintData1 , lprPrintData1);
         (*env)->ReleaseStringChars(env, jlprPrintData2 , lprPrintData2);
         (*env)->ReleaseStringChars(env, jlprCaseNo , lprCaseNo);
         (*env)->ReleaseStringChars(env, jlprReceiptNo , lprReceiptNo);
         return 1;
    the h file:
    /* DO NOT EDIT THIS FILE - it is machine generated */
    #include <jni.h>
    /* Header for class TestPrint */
    #ifndef _Included_TestPrint
    #define _Included_TestPrint
    #ifdef __cplusplus
    extern "C" {
    #endif
    * Class: TestPrint
    * Method: PrintDrugReceipt
    * Signature: (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)J
    JNIEXPORT jlong JNICALL Java_TestPrint_PrintDrugReceiptWrapper
    (JNIEnv *, jobject, jstring, jstring, jstring, jstring, jstring, jstring, jstring);
    #ifdef __cplusplus
    #endif
    #endif
    Note: the jstring input parameters are the chinese character. If i print out the jstring, it will display dirty character, why? and how to fix it? and the PrintDrugReceipt will expected accept the chinese character and print it to the printer.
    Thank you for you guys help.
    Matthew

    you can't use char...have to use a wchar....and look around at the wide character handling function in C/C++.

  • Access c library w/o using JNI

    I have a compiled shared library from vendor with no access to the source that is needed to interact with our Java code. I do have access to the library function definitions. Is there a way to utilize the "extern" functions from the compiled library with Java without having to write JNI that get compiled into the C library?
    For example, a function in the library is defined as: int isDiskOpen(const char *) which takes the name of the disk, and tells whether it is open ( 1,or 0). I can't write and compile into it with a Java_DiskUtils_isDiskOpen(JNIEnv *env, jobject obj, jstring dskName) wrapper to the C function.
    Is this possible?

    I am sort of new to JNI, and previously, I have put
    the wrapper in the same source as the "real" function,
    and compiled it into one library. You are saying use
    two libraries, one the original 3rd party lib, and the
    other my own wrapper library? How do you write a
    library to access another library?In the source you just include the third party header file and use the declarations it provides.
    From this source you can create a shared library in the same way you have done before.
    When you run the Java program you make sure both your wrapper shared library and your third party shared library are in your LD_LIBRARY_PATH.
    >
    I am also in Unix, not Windows.A minority developer then!

  • Problems using JNI and JSP in WebLogic 6.0

    Hello everybody. My problem is that I've got a Java class that is called from a JSP. That class connects to a C function and it returns a String. A want this string to be shown by the JSP. The code is:
    JSP
    <html>
    <head>
    <title>prueba JNI</title>
    </head>
    <body>
    <%@ page import="ejemplosJNI.*, conversiones.*;"%>
    <%
    Texto texto = new Texto();
    out.println(texto.realizado());
    %>
    </body>
    </html>
    Java class
    package ejemplosJNI;
    public class Texto
    private native String getLine(String prompt);
    String input = null;
    public static void main(String args[])
    Texto t = new Texto();
    static
    System.loadLibrary("MyImpOfPrompt");
    public String realizado()
    input = this.getLine("Mando una l�nea desde Java");
    return input;
    C function
    #include <stdio.h>
    #include <jni.h>
    #include "Texto.h"
    JNIEXPORT jstring JNICALL
    Java_Texto_getLine(JNIEnv *env, jobject obj, jstring prompt)
    char buf[128];
    const char str = (env)->GetStringUTFChars(env, prompt, 0);
    (*env)->ReleaseStringUTFChars(env, prompt, str);
    return (*env)->NewStringUTF(env, str);
    I compile de C function and put the .dll library in the 'bin' folder in webLogic.
    When I call the JSP, I get the next exception:
    Servlet failed with Exception
    java.lang.UnsatisfiedLinkError: getLine
    at ejemplosJNI.Texto.getLine(Native Method)
    at ejemplosJNI.Texto.realizado(Texto.java:19)
    at jsp_servlet._jsp._pruebasjni._prueba1._jspService(_prueba1.java:93)
    at weblogic.servlet.jsp.JspBase.service(JspBase.java:27)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubIm
    pl.java:213)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubIm
    pl.java:246)
    at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppSe
    rvletContext.java:1265)
    at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestIm
    pl.java:1622)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:137)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:120)
    Is there any place where I have to put the .dll?
    Is there any place where I have to put the generated .lib?
    Where do I have to put the Texto.h file generated with javah?
    Can anybody help me to solve this problem?
    Thanks in advance.

    Hi, jschell! Maybe you can see my problem if I give you the code. My Java class and the C funtions are:
    Java class
    package ejemplos.cadena;
    public class Texto
    private native String getLine(String prompt) throws Exception;
    String cadenaFinal = null;
    public static void main(String args[])
    Texto t = new Texto();
    static
    System.loadLibrary("LibreriaCadena");
    public String realizado(String cadena)
    try
    cadenaFinal = getLine(cadena);
    catch(Exception e)
    System.out.println(e.toString());
    return cadenaFinal;
    C code
    #include <stdio.h>
    #include <jni.h>
    #include "ejemplos_cadena_Texto.h"
    JNIEXPORT jstring JNICALL
    Java_ejemplos_cadena_Texto_getLine(JNIEnv *env, jobject obj, jstring prompt)
    int cero =0;
    int division = 10 / cero;
    const char str = (env)->GetStringUTFChars(env, prompt, 0);
    (*env)->ReleaseStringUTFChars(env, prompt, str);
    return (*env)->NewStringUTF(env, str);
    I have done something like "int division = 10 / cero;" in order to get an exception in my C code. When I run my Java class I get an error message and the application breaks. I would like to know how to catch the C exception in order to pass it to my Java class that can manage it into the try-catch clause. I have read I have to use something like "FindClass" or "ThrowNew", but my problem is that I have no idea about C programming.
    Can you help me?
    Thanks for your time.

  • Returning arrays using JNI

    Hi all,
    Hi,
    I am in the process of accessing the MS cryptoPI using java-jni-CryptoAPI. SO far i have been able to suceesfully acessing the cryptoapi functions. There are certificate stores istalled in our windows OS called "root", "CA" and "My" .Each of these stores have a lot of certificates installed . Till now i have written a program which opens the "My" cert store. In this case, it has only one certificate whose name is stored in pszNameString. In this case, the cert name is "AMS vivek" .I dont have any problem in passing the string back to java code if there is only one certificate involved. Supposing i retireve 2 certs,whose cert names are "AMS Vivek" and "Wipro Vivek" how do i pass them back to the java application. How do i store the names of the certificate in the native code and how do i pass them back to the java code??PLease help!
    import java.awt.*;
    import java.io.*;
    import java.lang.*;
    import java.applet.*;
    public class Testapp extends Applet {
         String ret=null;
    public void init(){
              System.out.println("in init");
              loaddll();
         public void loaddll(){
                        System.out.println("before loading DLL");
                        System.loadLibrary("Msgimpl");
                        System.out.println("After loading DLL");
         private native String crypto(String store);
    public void paint(Graphics g) {
              g.setColor(Color.blue);
              g.setColor(Color.magenta);
              g.drawString("call before native function", 25, 25);
              ret=crypto("My");
         g.drawString(ret, 25, 50);
              g.drawString("Finally", 25, 75);
    #define WIN32WINNT 0x0400
    #include <windows.h>
    #include <jni.h>
    #include <wincrypt.h>
    #define MY_ENCODING_TYPE (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)
    #include "Testapp.h"
    BOOL APIENTRY DllMain(HANDLE hModule,
    DWORD dwReason, void** lpReserved) {
    return TRUE;
    JNIEXPORT jstring JNICALL
    Java_Testapp_crypto(JNIEnv * jEnv,jobject obj,jstring jstore) {
         HCRYPTPROV               hProv;
              BOOL                    bResult;
              HCERTSTORE hStoreHandle = NULL;
              PCCERT_CONTEXT          pCertContext = NULL;
              char                    pszNameString[256];
              CRYPT_KEY_PROV_INFO *pCryptKeyProvInfo;
              DWORD                    dwPropId=0;
              DWORD                    cbData;
              const char *msg;
              jstring jstr;
              msg = (*jEnv)->GetStringUTFChars(jEnv, jstore,0);
              //printf("Before context\n");
              if (hStoreHandle = CertOpenSystemStore(NULL,msg))
              printf("The %s store has been opened. \n", msg);
              else
              printf("The store was not opened.\n");
              exit(1);
         while(pCertContext= CertEnumCertificatesInStore(hStoreHandle,pCertContext))
                                       // on the first call to the function,
              // this parameter is NULL
              // on all subsequent calls,
              // this parameter is the last pointer
              // returned by the function
              if(CertGetNameString(pCertContext,CERT_NAME_FRIENDLY_DISPLAY_TYPE,0,NULL,pszNameString,1000))
              printf("\nCertificate for %s \n",pszNameString);
                   else
                   printf("\nGetNameFailed\n");
         }//main while
         return (*jEnv)->NewStringUTF(jEnv, pszNameString);
         //(*jEnv)->ReleaseStringUTFChars(jEnv, jstore,msg);
         if (!CertCloseStore(hStoreHandle,0))
         //printf("Failed CertCloseStore\n");
         exit(1);
              //printf("After context\n");

    Testapp.h is the header file that java creates.It conatins the definition of the native methods to be used.u can create a header file using
    javah -jni Testapp(class file...u must forst compile the .java file)
    * DO NOT EDIT THIS FILE - it is machine generated */
    #include <jni.h>
    /* Header for class Testapp */
    #ifndef IncludedTestapp
    #define IncludedTestapp
    #ifdef __cplusplus
    extern "C" {
    #endif
    /* Inaccessible static: LOCK */
    /* Inaccessible static: dbg */
    /* Inaccessible static: isInc */
    /* Inaccessible static: incRate */
    #undef Testapp_TOP_ALIGNMENT
    #define Testapp_TOP_ALIGNMENT 0.0f
    #undef Testapp_CENTER_ALIGNMENT
    #define Testapp_CENTER_ALIGNMENT 0.5f
    #undef Testapp_BOTTOM_ALIGNMENT
    #define Testapp_BOTTOM_ALIGNMENT 1.0f
    #undef Testapp_LEFT_ALIGNMENT
    #define Testapp_LEFT_ALIGNMENT 0.0f
    #undef Testapp_RIGHT_ALIGNMENT
    #define Testapp_RIGHT_ALIGNMENT 1.0f
    #undef Testapp_serialVersionUID
    #define Testapp_serialVersionUID -7644114512714619750LL
    /* Inaccessible static: metrics */
    /* Inaccessible static: class_00024java_00024awt_00024Component */
    /* Inaccessible static: class_00024java_00024awt_00024event_00024ComponentListener */
    /* Inaccessible static: class_00024java_00024awt_00024event_00024FocusListener */
    /* Inaccessible static: class_00024java_00024awt_00024event_00024HierarchyListener */
    /* Inaccessible static: class_00024java_00024awt_00024event_00024HierarchyBoundsListener */
    /* Inaccessible static: class_00024java_00024awt_00024event_00024KeyListener */
    /* Inaccessible static: class_00024java_00024awt_00024event_00024MouseListener */
    /* Inaccessible static: class_00024java_00024awt_00024event_00024MouseMotionListener */
    /* Inaccessible static: class_00024java_00024awt_00024event_00024InputMethodListener */
    #undef Testapp_serialVersionUID
    #define Testapp_serialVersionUID 4613797578919906343LL
    /* Inaccessible static: dbg */
    /* Inaccessible static: class_00024java_00024awt_00024Container */
    /* Inaccessible static: class_00024java_00024awt_00024event_00024ContainerListener */
    /* Inaccessible static: nameCounter */
    #undef Testapp_serialVersionUID
    #define Testapp_serialVersionUID -2728009084054400034LL
    #undef Testapp_serialVersionUID
    #define Testapp_serialVersionUID -5836846270535785031LL
    * Class: Testapp
    * Method: listCertificate
    * Signature: (Ljava/lang/String;)[Ljava/lang/String;
    JNIEXPORT jobjectArray JNICALL Java_Testapp_listCertificate
    (JNIEnv *, jobject, jstring);
    * Class: Testapp
    * Method: certificateKey
    * Signature: (Ljava/lang/String;[B)V
    JNIEXPORT void JNICALL Java_Testapp_certificateKey
    (JNIEnv *, jobject, jstring, jbyteArray);
    #ifdef __cplusplus
    #endif
    #endif

  • Why the const char* filename can not open file?

    the jni pass the string, I then convert it to the
    const char* filename = env->GetStringUTFChars(fname,NULL);
    then I use the filename to opent the file but fails, what is the problem???
    FILE *fp= fopen(filename,"w"); // there are some problem here!!!
         fprintf(fp, "%s\n","wangyue fighting!");
    the error is as follows
    # An unexpected error has been detected by Java Runtime Environment:
    # EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x0bfc1a55, pid=7040, tid=11384
    # Java VM: Java HotSpot(TM) Client VM (10.0-b19 mixed mode windows-x86)
    # Problematic frame:
    # C [beattrack.dll+0x1a55]
    # An error report file with more information is saved as:
    # D:\programs\playAudio\hs_err_pid7040.log
    # If you would like to submit a bug report, please visit:
    # http://java.sun.com/webapps/bugreport/crash.jsp
    # The crash happened outside the Java Virtual Machine in native code.
    # See problematic frame for where to report the bug.
    #

    Danielwang wrote:
    the jni pass the string, I then convert it to the
    const char* filename = env->GetStringUTFChars(fname,NULL);
    then I use the filename to opent the file but fails, what is the problem???
    Same as your previous problem.
    FILE *fp= fopen(filename,"w"); // there are some problem here!!!No that is not where the problem is.

  • Getting list of methods/ fields using JNI ( REPOST)

    Hi All,
    Since I did noy get any response , I am reposting this....
    I am trying to get a list of all public methods & fields in a given class. But I am having trouble. Listing below shows the code I am using. In the example I am trying to get all the public methods of java.lang.String .
    But the code always prints out the 44 methods of java.lang.Class. . Can anyone help me out please ??
    jclass cls = env->FindClass("java/lang/String");
         if (cls == 0) {
              fprintf(stderr, "Can't find hello class\n");
              exit(1);
         else
              jclass jCls = env->GetObjectClass(cls);  // Get the java.lang.Class for String
                   // Get Method ID of getMethods()
              jmethodID midGetFields = env->GetMethodID(jCls, "getMethods","()[Ljava/lang/reflect/Method;");
              env->ExceptionDescribe();
              jobjectArray jobjArray = (jobjectArray)env->CallObjectMethod(jCls, midGetFields);
              jsize len = env->GetArrayLength(jobjArray);
              for(jsize i = 0 ; i < len ; i++)
                   jobject _strMethod = env->GetObjectArrayElement(jobjArray , i) ;
                   jclass _methodClazz = env->GetObjectClass(_strMethod) ;
                   jmethodID mid = env->GetMethodID(_methodClazz , "getName" , "()Ljava/lang/String;") ;
                   jstring _name = (jstring) env->CallObjectMethod(_strMethod , mid ) ;
                   char buf[128];
                   const char *str = env->GetStringUTFChars(_name, 0);
                   printf("\n%s", str);
                   env->ReleaseStringUTFChars(_name, str);
              }Cheers,
    KHK

    Forget my last post. It doesn't work at all (big-o-crash)!
    Try this instead. Maybe there is a way much simpler.
    The idea is to instanciate a String object, call getClass() on it, and from the returned object (a Class object) call getMethods().
        jclass cls = env->FindClass("java/lang/String");
        if (cls == 0) {
            fprintf(stderr, "Can't find hello class\n");
            exit(1);
        else {
            jobject strObj = env->AllocObject(cls);
            jmethodID midGetClass = env->GetMethodID(cls, "getClass", "()Ljava/lang/Class;");
            jobject clsObj = env->CallObjectMethod(strObj, midGetClass);
            jclass jCls = env->GetObjectClass(clsObj);
            jmethodID midGetFields = env->GetMethodID(jCls, "getMethods", "()[Ljava/lang/reflect/Method;");
            jobjectArray jobjArray = (jobjectArray)env->CallObjectMethod(clsObj, midGetFields);
            jsize len = env->GetArrayLength(jobjArray);
            jsize i;
            for (i = 0 ; i < len ; i++) {
                jobject _strMethod = env->GetObjectArrayElement(jobjArray , i) ;
                jclass _methodClazz = env->GetObjectClass(_strMethod) ;
                jmethodID mid = env->GetMethodID(_methodClazz , "getName" , "()Ljava/lang/String;") ;
                jstring _name = (jstring)env->CallObjectMethod(_strMethod , mid ) ;
                const char *str = env->GetStringUTFChars(_name, 0);
                printf("\n%s", str);
                env->ReleaseStringUTFChars(_name, str);

  • JVM crashes when converting jstring to native string

    Hi ,
    I am trying to convert a jstring to a char * . My main program is in C.
    I tried calling the two methods :
    const char str = (env)->GetStringUTFChars(env, myJstring, 0);
    and
    const char *result = JNU_GetStringNativeChars(env, myJstring);
    Both the times the VM crashed. I copied the code for both the above mentioned functions from sun's website examples.
    Any help appreciated.
    thanks,
    Sanjay

    Try this:
    JNIEXPORT void JNICALL my_native_method
      (JNIEnv * env, jobject obj, jstring jnewValue)     
      jboolean isCopy;
      const char* newValue = env->GetStringUTFChars(jnewValue, &isCopy);
      // release string if possible
      if(isCopy == JNI_TRUE) {
        env->ReleaseStringUTFChars(jnewValue, newValue);
    } But be aware of one thing:
    The JNIEnv pointer has to be valid in the current thread, if not the JVM will crash. The JNIEnv pointer is always valid in the example above, since this is the implementation of a native method. The JNIEnv is only valid in the thread it is created in.
    Hope this can be of any help :)

Maybe you are looking for

  • After upgrading to mountain lion my usb drive gets disconnected

    I have a late 2009 iMac that just installed Mountain Lion. Every single USB external drive that is connected, shortly after a while gets unmounted. I tried with disabling sleep mode for HD etc and no success. Then I tried USB card reader and same exa

  • Itunes wont sync, Error 1651. iTunes 10.5.1, Windows 7, iPhone 3G

    My iTunes has stopped syncing, since the last software update. It reports errors such as unable to establish apps, photo problems. When I go to the Summary and Check for Update I receive the following error: iTunes could not check for an update to th

  • Runtime engine files 8.2

    Hi, Since most users of my written program are users with "restricted right" acounts under Windows XP I copied the Runtime engine files of LV7.11 manualy by copying the "Program Files\National Instruments\LabVIEW 7.1\Shared\LabVIEW Run-Time\7.1" file

  • Installing Illustrator CS6

    I don't know what else to try...Need Help! I am clicking the "Download" button, but nothing happens. I'm using Windows 7, and Google chrome as my browser. Thanks for your help in advance! This is my first time using CC, so I'm sure I am overlooking s

  • For transport different quatation from differnt agent in SAP

    Is it possible in standard SAP,For transport different quatation from differnt agent ? If it possible,how?