这是一个思考的方法。
关于我首先做出的假设的一些背景知识。
听起来您有一些函数libraryFunction ()
返回指向 a 的指针struct theStruct
。但是,实际布局struct theStruct
取决于您的应用程序在其上运行的特定系统。在这个结构中是您需要访问的一些信息。您不指定库函数的调用参数或签名,如果指向的指针struct theStruct
作为函数值返回,或者指向指针的指针是参数列表的一部分。我会假设它是一个函数返回值。
创建一个您为所需信息定义的结构。创建两个文件,每个文件都有一个函数,该函数接受一个 void 指针和一个指向新结构的指针,然后用库提供的结构中所需的数据填充结构。这两个文件中的每一个都将使用指定的特定系统目标(SystemA 或 SystemB)进行编译,以便您的转换函数将根据目标系统解释库函数提供的结构,并用您想要的数据填充您的结构。
系统 A 的文件 1
// copy of the struct used in System A which is in the library header file
// put here for reference only as should be in the header file
struct theStruct {
int fd;
unsigned int flags;
struct config config; // only in System A
int foo; // in both systems
int bar; // only in System A
};
// my struct that contains the data from struct theStruct that I want
// would be in a header file included into each of these files but here for reference
struct myConvertStruct {
int foo;
};
void convert2SystemA (void *structPtr, struct *myStruct)
{
myStruct->foo = ((struct theStruct *)structPtr)->foo;
}
系统 B 的文件 2
// copy of the struct used in System B which is in the library header file
// put here for reference only as should be in the header file
struct theStruct {
int fd;
unsigned int flags;
int foo; // in both systems
int foobar; // only in system B
};
// my struct that contains the data from struct theStruct that I want
// would be in a header file included into each of these files but here for reference
struct myConvertStruct {
int foo;
};
void convert2SystemB (void *structPtr, struct *myStruct)
{
myStruct->foo = ((struct theStruct *)structPtr)->foo;
}
文件 3 使用转换函数
// my struct that contains the data from struct theStruct that I want
// would be in a header file included into each of these files but here for reference
struct myConvertStruct {
int foo;
};
{
struct myConvertStruct myStruct;
// some function body and now we come to the library call
if (mySystem == SystemA) {
void *pStruct = libraryFunction (......);
convert2SystemA (pStruct, &myStruct);
} else if (mySystem == SystemB) {
void *pStruct = libraryFunction (......);
convert2SystemB (pStruct, &myStruct);
} else {
// some error conditions
}
// now use the data that you have pulled as you want to use it
}