我目前正在将用 C 编写的 DLL 改编为 Java,并且我在使用 memcpy 和 memset C 函数时遇到问题。
这是我要转换的内容(不是完整的代码):
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));
对于memcpy,我知道有System.arraycopy,但是当按照以下方式使用它时,这不是我所期望的
System.arraycopy(trans_data, 2, buff, 2, totalsize);
考虑到 C memcpy 和 Java arraycopy 中目标/源参数的顺序不同
C 的
memcpy(b+2, a+1, 2);
相当于 Java 的 System.arraycopy(a, 1, b, 2, 2);
,它的意思是“将数组 a 中的位置 1 和 2 复制到数组 b 的位置 2 和 3”。
尝试重新排序参数。
我们可以使用
Arrays.fill()
方法填充原始数组,正如 @DieMartin 所说的那样。
代码:
int[] arr = new int[10];
// filling array with a default value
Arrays.fill(arr, -1);
System.out.println("after filling array with -1: " + Arrays.toString(arr));