I was trying to find effective way to read shared memory in form of array of struct (in C):
typedef struct the_struct {
int id;
int data;
} the_c_struct;
static the_c_struct *the_struc_ptr = NULL;
Currently I use following JNA Structure
code to retrieve the data from shared memory:
public class MyCStruc extends Structure {
public int id;
public int data;
@Override
protected List getFieldOrder() {
return Arrays.asList(new String[]{"id", "data"});
}
@Override
public void useMemory(Pointer m, int offset) {
super.useMemory(m, offset);
super.read();
}
@Override
public void useMemory(Pointer m) {
super.useMemory(m);
super.read();
}
}
And read shared memory using native implementation of shmget
and shmat
:
memId = NativeLib.INSTANCE.shmget(0x999, memSize, 0);
CStructPtr = NativeLib.INSTANCE.shmat(memId, null, 0);
MyCStruc cs=new MyCStruc();
for (int i=0;i<CStructArraySize;i+=8) {
cs.useMemory(CStructPtr,i);
// to read a record of struct array
// do something with the data
}
Above code is actually worked, but I guess I can do something more effective to read array of struct? right?
Note: size of array of struct is dynamic, but I can managed to get the size of the shared memory.