将 (ptr to const) 转换为 (ptr to uint8)

Casting a (ptr to const ) to (ptr to uint8)

在"C"中有没有办法将(ptr to const structure)转换为(ptr to uint8)

以下函数需要 (ptr to uint8)

memcopy( (uint8 *) destination, (uint8 *) source , uint16 _size);

该函数打算将类型为 ((ptr to const)) 的缓冲区复制到另一个缓冲区

我知道在 C++ 中我可能会使用 const_cast 来抛弃(移除)constness 或 volatility。但是 C 呢?

目前情况如下: 假设我有一个结构 main_S

struct main_S {
strcut1 xxxx1
strcut2 xxxx2
strcut3 xxxx3
}

指向 main_S strcut 的指针是 (ptrcnst_Main),它是指向 const 的指针。

我需要复制 main_S 的第二个元素 (xxxx2) 所以我将执行以下操作

strcut2 dest;
memcopy( (uint8 *) &destination, (uint8 *) ptrcnst_Main->xxxx2 , SizeOf(strcut2));

但这永远行不通。我一直有错误,我无法将 ptr const 转换为 ptr-uint8

对于 C,您可以使用常规的 C 风格转换来摆脱常量。例如:

void f(const int *src,int *dst,int n)
{
    memcopy((uint8_t*)dst,(uint8_t*)src,n*sizeof(int));
}

请注意,实际写入最初声明为 const 的对象是未定义的行为,所以要小心。

更新

我刚看了你的评论,越来越奇怪了...代码很近似,但我会尽力解决你的问题。

strcut2 dest;
memcopy( (uint8 *)&dest, (uint8 *)&(ptrcnst_Main->xxxx2) , SizeOf(strcut2));

尝试在您的 ptrcnst_Main->xxxx2 前面添加一个符号 (&),并像我一样放置括号。


通常,当您将数据从一个缓冲区复制到另一个缓冲区而不对源缓冲区应用任何更改时,您将变量声明为常量指针,因为它不会改变 !这是一个 source 缓冲区。所以在这里,你的指针 source 应该是 const uint8 *source。就算是常量指针,也能读到里面的值。

const 限定符放在非可变数据上(阅读 "data which doesn't need to change"),对您和您的每一位同事来说都是一个很好的做法。

结论 您不需要将任何从 const 转换为非 const。仍然可以读取常量变量。

但是,我会回答你原来的问题:

Is there a way in "C" to cast a (ptr to const) to (ptr to uint8)?

在 C 中,您只需按如下方式转换:(type) variable

例如:

const char* c1 = malloc(sizeof(char) * 5);
char* c2 = (char*)c1; // cast is here
for (int i = 0; i < 5 ; i++) {
   c2[i] = 'i';
}
printf("%s\n", c1);

但是删除常量是一个非常糟糕的做法。如果它是常数,通常是故意的。

注意:该代码在很多方面都不好,但为了演示目的我保持简单。