Parameter passing in native a method [duplicate]

為{幸葍}努か 提交于 2019-12-11 11:43:31

问题


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:


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.



来源:https://stackoverflow.com/questions/12990929/parameter-passing-in-native-a-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!