Parameter passing in native a method

511 Views Asked by At

Possible Duplicate:
jni converting jstring to char *

There is a function on С (traverser.c module)

long int
Traverser(const char * sTraversingRoot) 
{
    long int nCount;
    struct stat rStatBuf;
    time_t nTime;
    char sActualPath[512];
    PGconn *pConn;

    // Open DB connection
    sprintf(sConnInfo, 
        "hostaddr=%s port=%s connect_timeout=50 dbname=%s user=%s password=%s",
        sIP, sPort, sDBName, sLogin, sPassword);
    pConn = PQconnectdb(sConnInfo);
    if (PQstatus(pConn) == CONNECTION_BAD) {
        AddErrorToLog("No connect\n");
        return 0;
    }

    GetActualPath(sActualPath, sTraversingRoot);

    if (*sActualPath) {
        stat(sActualPath, &rStatBuf);
    } else {
        stat("/", &rStatBuf);
    }

    if (nClock)
        nTime = time(NULL);

    if(S_ISREG(rStatBuf.st_mode)) {
        nCount = 1;
        ProcessFile(pConn, sActualPath);
    }

    if(S_ISDIR(rStatBuf.st_mode)) {
        nCount = _Traverser(pConn, sActualPath);
    }

    if (nClock)
        fprintf(stdout, "Total time : %u second(s)\n", time(NULL) - nTime);
    // Close DB connection
    PQfinish(pConn);

    return nCount;
}

I want to create native with the same name a method on Java

public native void Traverser(String path)

Respectively in the traverser.c module there will be a function

JNIEXPORT void JNICALL Java_ParallelIndexation_Traverser(JNIEnv *env, jobject obj, jstring path) 

The Java_ParallelIndexation_Traverser function is a Traverser function wrapper from the traverser.c module.The question is: How to call a module from Traverser traverser.c in Java_ParallelIndexation_Traverser, passing it the parameter jstring path, thus converting it to a const char * (signature Traverser see above)?

1

There are 1 best solutions below

8
On

Did I understand your question correctly: how to implement Java_ParallelIndexation_Traverser so that it calls the unmanaged Traveser function?

If so, here's how:

JNIEXPORT void JNICALL Java_ParallelIndexation_Traverser(JNIEnv* env, jobject obj, jstring path)
{
    const jbyte* path2 = env->GetStringUTFChars(path, nullptr);
    if (path2 == nullptr)
        return;

    ::Traverser(path2);

    env->ReleaseStringUTFChars(path, path2);
}

Edit:

Explanation: JNIEnv::GetStringUTFChars converts a jstring to a byte array. You then need to call JNIEnv::ReleaseStringUTFChars to deallocate that byte array.