使用 void* 的 C 通用可编辑函数
我陷入了一些问题。
我需要编写一些像 memcpy(void*, const void*) 这样的函数,其签名应该是:
void arrayCopy(void *dest, int dIndex, const void *src, int sIndex, int len)
我注意到,在许多 memcpy 实现中,我们都会强制转换 void * 到 char*,但我认为这不是我的情况,因为 arrayCopy
函数需要在包括 structs
在内的许多类型的数组上使用。
那么,我怎样才能做到这一点呢?
编辑: 源代码可能是这样的:
#include <stdio.h>
#include <string.h>
void arrayCopy(void *, int, const void *, int, int, size_t);
int main(void)
{
int i;
int dest[10] = {1};
int src [] = {2, 3, 4, 5, 6};
arrayCopy(dest, 1, src, 0, 5, sizeof(int));
for (i=0; i<10; i++) printf("%i\n", dest[i]);
return 0;
}
void arrayCopy(void *dest, int dIndex, const void *src, int sIndex, int len, size_t size)
{
char *cdest = (char*) dest;
const char *csrc = (char*) src;
int i;
len *= size;
if (dest == src)
{
printf("Same array\n");
}else
{
cdest += (dIndex * size);
csrc += (sIndex * size);
for (i=0; i<len; i++)
*cdest++ = *csrc++;
}
}
谢谢。
I fall in some problem.
I need to write some function like memcpy(void*, const void*)
, which its signature should be:
void arrayCopy(void *dest, int dIndex, const void *src, int sIndex, int len)
I noticed that, in many implementation of memcpy
, we cast void* to char*, but I think this is not the case of me, as the arrayCopy
function needed to be used on arrays of many types including structs
.
So, how can I accomplish this?
EDIT:
the source code might be something like that:
#include <stdio.h>
#include <string.h>
void arrayCopy(void *, int, const void *, int, int, size_t);
int main(void)
{
int i;
int dest[10] = {1};
int src [] = {2, 3, 4, 5, 6};
arrayCopy(dest, 1, src, 0, 5, sizeof(int));
for (i=0; i<10; i++) printf("%i\n", dest[i]);
return 0;
}
void arrayCopy(void *dest, int dIndex, const void *src, int sIndex, int len, size_t size)
{
char *cdest = (char*) dest;
const char *csrc = (char*) src;
int i;
len *= size;
if (dest == src)
{
printf("Same array\n");
}else
{
cdest += (dIndex * size);
csrc += (sIndex * size);
for (i=0; i<len; i++)
*cdest++ = *csrc++;
}
}
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
“char *”只是一堆字节,C 中的所有内容最终都是字节 - 您可以将指向任何数据结构的指针转换为 char* (您还需要知道该结构在内存中的大小)
"char * " is just a bunch bytes, everything in C is ultimately bytes - you can cast a pointer to any data structure to char* (you will also need to know the size in memory of the structure)
该函数必须具有元素大小信息,例如:
The function must have an element-size info, eg:
您不能使用
void
类型的对象。标准不允许这样做。因此,您需要抛弃 void,最好使用的类型是unsigned char
。标准保证unsigned char
可以访问系统中可表示的任何其他类型的所有位。You cannot work with objects of type
void
. The Standard doesn't allow that. So you need to cast the void away, and the best type to use isunsigned char
. There's a guarantee by the Standard thatunsigned char
can access all bits of any other type representable in your system.