我有以下两个结构。我需要从复制d, e, f到source,然后destination使用memcpy和offsetof。我怎样才能做到这一点?
struct source
{
int a;
int b;
int c;
int d;
int e;
int f;
};
struct destination
{
int d;
int e;
int f;
};
Run Code Online (Sandbox Code Playgroud) 我正在尝试在C++(Linux)中为我的一个套接字添加套接字过滤器.在套接字过滤器中,我需要获取struct fork_proc_event的偏移量,它嵌套在另一个结构中.定义看起来像这样(cn_proc.h):
struct proc_event {
...
union {
...
struct fork_proc_event {
__kernel_pid_t parent_pid;
...
} fork;
...
} event_data;
...
};
在CI中会这样做:
int off = offsetof(struct fork_proc_event, parent_pid);
但是我正在用C++开发.如果我尝试这样做:
int off = offsetof(proc_event::fork_proc_event, parent_pid);
我收到以下错误:
error: expected type-specifier error: expected `,' error: expected `)' before ',' token
offsetof()行应该如何?
我有一个struct(Member),它只能用作其他struct(Container)中的数据成员.按照惯例,成员的名字总是m.成员是否有可靠的方法来获取包含结构的地址?
template<typename Struct>
struct Member;
{
const Struct& s = ??;
// this - &Struct::m
};
struct Container
{
Member<Container> m;
};
Run Code Online (Sandbox Code Playgroud)
我希望可能使用指向成员的指针&Container::m可能有助于从Member对象本身的地址计算回来?
我想通过组合offsetof宏和memcpy,从某个元素开始向前复制结构的一部分,如下所示:
#include <stdio.h>
#include <string.h>
#include <stddef.h>
struct test {
int x, y, z;
};
int main() {
struct test a = { 1, 2, 3 };
struct test b = { 4, 5, 6 };
const size_t yOffset = offsetof(struct test, y);
memcpy(&b + yOffset, &a + yOffset, sizeof(struct test) - yOffset);
printf("%d ", b.x);
printf("%d ", b.y);
printf("%d", b.z);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我希望这会输出,4 2 3但它实际上输出4 5 6好像没有发生复制一样。我做错了什么?