我需要在我的C ++代码中使用一些C定义的结构。下面是C头文件中的结构
#ifdef __cplusplus
extern "C" {
#endif
typedef struct TestParameters {
long p1;
long p2;
long p3;
} TestParameters_t;
#ifdef __cplusplus
}
下面的代码编译但是按照标准定义和有效的行为接收C实例作为参考并使用它?
TestParameters_t testParams;
test(testParams);
// Is it valid to receive a C struct instance as a reference in C++ code
void test(TestParameters_t &testParams)
{
}
答案 0 :(得分:4)
是的,即使结构来自C头文件,您也可以像使用C ++头文件中定义的结构一样使用它。
使用其引用或地址传递结构比使用其值更好。
如果函数无法修改,请不要忘记将其标记为 const 。
void test( const TestParameters_t &testParams)
{
// Won't modify testParams;
}
或
void test( TestParameters_t &testParams)
{
// Will modify testParams;
}
答案 1 :(得分:1)
只要您在C ++代码中使用test
,不仅允许使用引用,而且建议使用参数传递参数。
作为非法使用的示例,您可以尝试将其强制转换为void (*)(TestParameters_t*)
并将此指针作为回调传递给某些C代码 - 这是非法的并且会调用未定义的行为。
答案 2 :(得分:1)
是的,这在C ++中可以正常工作。
通常,C是C ++的子集,但也有例外。正常struct
定义和用法不是其中之一。
维基百科在完整列出例外情况方面做得很好:http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B#Constructs_valid_in_C_but_not_in_C.2B.2B
当你编写C ++时,我会提到A.G.关于传递const
引用的观点。
我认为你知道extern "C"
阻止了C ++所做的名称修改,所以C extern
范围内定义的任何内容也可以被C使用?如果您只打算在C ++代码中使用struct
。我建议删除所有extern
内容。另请注意,如果您只是在C ++中,则不再需要typedef
或后缀名称。
在C ++中,您可以像这样定义struct
:
struct TestParameters {
long p1;
long p2;
long p3;
};
然后简单地使用它:TestParameters
。
但仅如果您要删除C支持,则执行此操作。