简体   繁体   English

Java和JNI全局变量

[英]Java and JNI global variables

I need help, because i don't known what to do. 我需要帮助,因为我不知道该怎么办。 I'm newbie in JNI. 我是JNI的新手。

I'm developing a Android application and it has to use a especific protocol (OpenIGTLink). 我正在开发一个Android应用程序,它必须使用especific协议(OpenIGTLink)。

To use this protocol I use a C library. 要使用此协议,我使用C库。 The problem is that I need to define a global variable to store the conection. 问题是我需要定义一个全局变量来存储连接。 You can see in the next example: 您可以在下一个示例中看到:

igtl::ClientSocket::Pointer socket;


Java_es_iac_iactec_infraredsend_Comunicacion_OpenIGTLink_connect(
    JNIEnv *env,
    jobject mjobject,
    jstring host,
    jint port) {
socket = igtl::ClientSocket::New();

const char *chost = env->GetStringUTFChars(host, 0);

int r = socket->ConnectToServer(chost, port);
if (r != 0) {

    return (jstring) "Cannot connect to the server.";
}

return (jstring) "ok";
}

and in other method iwant to do: 并想做的其他方法是:

 Java_es_iac_iactec_infraredsend_Comunicacion_OpenIGTLink_send() {
    igtl::ImageMessage::Pointer imgMsg = igtl::ImageMessage::New();
    imgMsg->SetDimensions(size);
    imgMsg->SetSpacing(spacing);
    imgMsg->SetScalarType(scalarType);
    imgMsg->SetDeviceName("ImagerClient");
    imgMsg->SetSubVolume(svsize, svoffset);
    imgMsg->AllocateScalars();
    imgMsg->Pack();

    socket->Send(imgMsg->GetPackPointer(), imgMsg->GetPackSize());
 }

I don't know if I have to declare a java global variable to store de socket object and access it from JNI or if it's possible to define socket like a global variable in the cpp file. 我不知道是否必须声明一个Java全局变量来存储de socket对象并从JNI访问它,或者是否有可能像cpp文件中的全局变量一样定义socket。

Thank you to all and sorry for my english. 谢谢大家,对不起我的英语。

Maybe, it's not the best way but we are doing it so. 也许这不是最好的方法,但我们正在这样做。 We are returning a pointer from JNI to Java as jlong and passing it to every call. 我们将JNI的指针作为jlong​​返回到Java,并将其传递给每个调用。 It works like a self pointer to the object in methods. 它就像方法中对象的自指针一样工作。 In your case, it will look somehow like this 在您的情况下,它将看起来像这样

jlong Java_es_iac_iactec_infraredsend_Comunicacion_OpenIGTLink_connect(
     JNIEnv *env,
     jobject mjobject,
     jstring host,
     jint port) {
     /*some code*/
     return reinterpret_cast<jlong>(socket);
 }

and then 接着

 Java_es_iac_iactec_infraredsend_Comunicacion_OpenIGTLink_send(jlong pointer) {
    /*some code*/
    igtl::ClientSocket::Pointer socket = reinterpret_cast<igtl::ClientSocket::Pointer>(pointer)
    socket -> Send(imgMsg->GetPackPointer(), imgMsg->GetPackSize());
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM