Passing an object including java Objects to a C library.


Very similar to including Java Strings:
The passed object, WebSiteVisit:

package helloworld;

/**
*
* @author thomas
*/
public class WebSiteVisit {
/** URL of the web page that linked user to this one */
public String refererURL;
public String pageVisited;
public int ipAddress;
IPAddress ipAddr;

/** Creates a new instance of WebSiteVisit */
public WebSiteVisit() {
}

public WebSiteVisit(String referer, String page, int ip) {
this.refererURL = referer;
this.ipAddress = ip;
this.pageVisited = page;
this.ipAddr = new IPAddress(ip);
}
}

The embedded object, IPAddress:

package helloworld;

/**
*
* @author thomas
*/
public class IPAddress {
public int byte1, byte2, byte3, byte4;
/** Creates a new instance of IPAddress */
public IPAddress() {
}
public IPAddress(int address) {
byte1 = (address & 0xff000000) >> 24;
byte2 = (address & 0x00ff0000) >> 16;
byte3 = (address & 0x0000ff00) >> 8;
byte4 = address & 0x000000ff;
}

}

The C source to the dynamic library, including the IPAddress object access.

JNIEXPORT void JNICALL Java_helloworld_Main_nativePrintNumber
(JNIEnv *env, jobject obj, jint ji)
{
jfieldID fid;
jint version;
jclass c;
c = (*env)->GetObjectClass(env, obj);
fid = (*env)->GetFieldID(env, c, "version_number", "I");
version = (*env)->GetIntField(env, obj, fid);
(*env)->SetIntField(env, obj, fid, ji*ji);
printf("::: %d, %dn", fid, version);
hello_number(ji);
}
JNIEXPORT void JNICALL Java_helloworld_Main_nativePrintObject
(JNIEnv *env, jobject ths, jobject wsv)
{
jfieldID fid;
jint ipAddress;
jstring jPageVisited;
char *pageVisited;
jstring jRefererURL;
char *refererURL;
jclass c;
jobject ipObject;
jclass ipObjectClass;
jint byte1, byte2, byte3, byte4;

c = (*env)->GetObjectClass(env, wsv);

.
.
.

fid = (*env)->GetFieldID(env, c, "ipAddr", "Lhelloworld/IPAddress;");
if(!fid) {
return;
}
ipObject = (*env)->GetObjectField(env, wsv, fid);
ipObjectClass = (*env)->GetObjectClass(env, ipObject);

fid = (*env)->GetFieldID(env, ipObjectClass, "byte1", "I");
byte1 = (*env)->GetIntField(env, ipObject, fid);

fid = (*env)->GetFieldID(env, ipObjectClass, "byte2", "I");
byte2 = (*env)->GetIntField(env, ipObject, fid);

fid = (*env)->GetFieldID(env, ipObjectClass, "byte3", "I");
byte3 = (*env)->GetIntField(env, ipObject, fid);

fid = (*env)->GetFieldID(env, ipObjectClass, "byte4", "I");
byte4 = (*env)->GetIntField(env, ipObject, fid);

printf("wsv.ipAddr = %d.%d.%d.%dns", byte1, byte2, byte3, byte4);
}

Leave a Reply

%d bloggers like this: