当你无法修改现有的结构定义时,你所要求的是不可能的。但是,您仍然可以通过一些OO风格的编程来自动执行功能。以下所有内容假定结构中的数据字段长度相同,并且包含相同大小的元素,如示例中所示。
基本上,你用自己的容器包装现有的结构。你可以把这个头文件:
/* Forward declaration of the wrapper type */
typedef struct s_wrapperStruct wrapperStruct;
/* Function pointer type for an updater function */
typedef void (*STRUCT_UPDATE_FPTR)(wrapperStruct* w, aStruct* src);
/* Definition of the wrapper type */
struct s_wrapperStruct
{
STRUCT_UPDATE_FPTR update;
aStruct* ap;
bStruct* bp;
};
然后你就可以可以创建你用它来创建您的同步结构对避免同步逻辑暴露给感兴趣各方工厂式的模块。实现一些简单的功能。
/* The updater function */
static void updateStructs(wrapperStruct* w, aStruct* src)
{
if ((w != NULL) && (src != NULL))
{
/* Copy the source data to your aStruct (or just the data field) */
memcpy(w->ap, src, sizeof(aStruct));
/* Sync a's data field to b */
sync(w); /* Keep this as a separate function so you can make it optional */
}
}
/* Sync the data fields of the two separate structs */
static void sync(wrapperStruct* w)
{
if (w != NULL)
{
memcpy(w->bp->data, w->ap->data, sizeof(w->bp->data));
}
}
然后在你的工厂函数可以创建包裹对。
/* Create a wrapper */
wrapperStruct syncedPair = { &updateStructs, &someA, &someB };
然后,您可以在需要的地方通过,例如,正在更新您的aStruct
,并使用它像这样的过程:
/* Pass new data to the synced pair */
syncedPair.update(&syncedPair, &newDataSource);
因为C不是被设计成一个面向对象的语言,它不具有this
指针,你需要通过明确的包装围绕指针。从本质上讲,这就是C++幕后的情况,编译器为您节省了额外的麻烦。
如果您需要将单个aStruct
同步到多个bStruct
s,将指针更改为数组指针并相应地修改其余部分应该非常简单。
这可能看起来像一个过于复杂的解决方案,但是当您实现逻辑一次时,它可能会帮助您节省维护中的一些体力劳动。
那不是这是如何工作的。分配'a.data [0] =(char)b.data [0]'等等。如果你喜欢,可以使用for循环。 – Magisch
在'bStruct'中,您需要将'char data [8]'更改为'char * data',所以答案是否定的。 – user3386109
数组不指向数据。并且不可分配。查看如何复制数组,应该有许多重复项。 – juanchopanza