javacmemcpy

memcpy and memset function to java


I am currently adapting a DLL written in C to Java and I am having problems with the memcpy and memset C functions.

Here is what I want to convert (it's not the whole code) :

    int res = 0;
    int bytes_written = 0;
    int totalsize;
    int reportid;
    hid_device *handle;
    unsigned char trans_data[64];
    unsigned char *buf;

    buf = (*env)->GetByteArrayElements(env, data, NULL);


    memcpy(trans_data+2,buf+bytes_written+2,totalsize);
    memset(trans_data+2+totalsize,0,64-(totalsize+2));   

For memcpy, I know there's System.arraycopy but when using it the following way, it's not what I expect

        System.arraycopy(trans_data, 2, buff, 2, totalsize);

Solution

  • Take into account that the order of destination/source parameters is different in C memcpy and Java arraycopy

    C's memcpy(b+2, a+1, 2); is equivalent to Java's System.arraycopy(a, 1, b, 2, 2); and it means "copy positions 1 and 2 from array a into positions 2 and 3 of array b".

    Try reordering your parameters.