I have created one native application in android that is working fine. This application is based on socket programing. so for that first i have to open that port by which i want to process my data , then processing code after that need to close. but problem is that as i am new in ndk programing i am able to open and process data in same function but i want a modular approach. first i want to make one open function then senddata and close. for that i need to create some global variable so that i could use them in my other function. like bellow:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LOG_TAG "native"
int skt; // i want to use skt and ifr values
struct ifreq ifr;
JNIEXPORT jint JNICALL Java_com_can_demo_NativeControls_Open(JNIEnv * env, jobject obj, jstring port)
{
if ((skt = socket(PF_, SOCK_RAW, _RAW)) < 0) {
LOGI( "socket not opend");
}
strcpy(ifr.ifr_name, port);
if( ioctl(skt, SIOCGIFINDEX, &ifr) < 0)
{
LOGI( "interface not opend");
}
addr._family = AF_;
addr._ifindex = ifr.ifr_ifindex;
if(bind (skt, (struct sockaddr*)&addr, sizeof(addr)) <0 )
{
LOGI( "bind Error");
}
}
JNIEXPORT jint JNICALL Java_com_can_demo_NativeControls_Send(JNIEnv * env, jobject obj, jstring path)
{
const jbyte *str;
frame._id = 0x123;
str = (*env)->GetStringUTFChars(env, path, 0);
strcpy( frame.data, str );
frame.can_dlc = strlen( frame.data );
int bytes_sent = write( skt, &frame, sizeof(frame) );
return bytes_sent;
}
now i have two function: open and sendData
in open function i am initializing some value in skt and ifr. and want to access those data in my senddata function. But when i print my log that time open function is working properly but sendData function is not able to access skt value that is initializing in open function. default its coming “0”. please guide me how can i achieve this.
First of all,
0is a perfectly correct value for a socket. So, your global variable is accessed as expected.But your code requires improvement. Some technical issues I explained in a comment. But I would strongly suggest not to use global variables the way you do in this snippet. The recommended way to treat native handles (e.g. pointers) is to return the value to Java (it could be
jlong) and pass it back from Java to native when your JNI function must use this value. There are techniques that allow the native code to access fields of the Java object to set/retrieve such information, but in the simple case like yours it’s an overshoot. Here is a simple example in Java: