I know we cannot access address of an Object safely in Java and we should never try to do something like this. But i need to convert this C code to Java. Value is always of size 8 bits
. The C code is like this:
void merge(int value,unsigned short* outp, int x,int y, int width)
{
unsigned char *outc;
outc=(unsigned char *) outp + y*width +x;
*outc=value;
}
To convert it into Java I have converted unsigned short* outp
to short outp[]
and unsigned char* outc
to short outc[]
. Then i can assign values in parts. But the problem i am facing is that when this function is called in a loop by some other function the width is incremented each time and only one byte is assigned to a particular cell..
I tried this Java code:
void merge(int value, int outp[], int x, int y, int width)
{
if(outp[y*width + x] >0)
{
outp[y*width+x]=outp[y*width+x]<<8 +value;
}
else
{
outp[y*width+x]=value;
}
}
How can i do this. Please help. Thanks.
It is not "possible" in java that does not have pointers. It has references that are irrelevant for primitive type like char
.
So, in java we typically use method that returns value instead of returning the value via pointer like C programmers do:
char merge(int value,int x,int y, int width) {
char outchar;
/// your code...
return outchar;
}
I have no idea what your code should do. To me it looks like it only sets the lower byte of a short to the given value and the shift in your java code seems out of place. Since you for some reason replaced short[] with int[] i don't know if the following will help:
void merge(int value,short[] outp, int x,int y, int width){
int address = y*width +x;
short temp = outp[address];
temp &= 0xFF00;//keep the high order bits of the old value
temp |= (short)(value & 0x00FF);//set the low order bits
outp[address] = temp;
}
Your C code looks like pointer arithmetic to find the address of a cell at a particular location in a grid, then set the value at that location.
For your Java code I would recommend a completely different approach. What data structure does your calling code use for the grid? You could use a class which models the grid, and includes a setValue(x,y) method. How the class models the grid internally is up to you - it could use a 2 dimensional array.
As a C programmer who tried to use Java for a project, I can certainly identify with your woes.
To resolve your problem, I would rather try to access your 2D data a 1D Java bytearray.
This will make it trivial to access the (row * col) byte and you will spare the need for this wrapper code (which will be very costly in a loop).
Whether you will allocate the array from Java or from C depends on your project but JNI calls make both solutions possible.
Good luck!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.