Referencing a C structure in C ++
I need to use some C defined structures in my C ++ code. Below is the structure in the C header file
#ifdef __cplusplus
extern "C" {
#endif
typedef struct TestParameters {
long p1;
long p2;
long p3;
} TestParameters_t;
#ifdef __cplusplus
}
Below code compiles, but is the behavior defined and valid according to the standard to get an instance of C as a reference and use it?
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)
{
}
source to share
Yes, even if the structure is derived from a C header file, you can use it in the same way as for the structure defined in the C ++ header file.
It is better to pass structures using your link or its address than using its value.
Just remember to mark it as const if the function doesn't change it.
void test( const TestParameters_t &testParams)
{
// Won't modify testParams;
}
or
void test( TestParameters_t &testParams)
{
// Will modify testParams;
}
source to share
As long as you are test
only using in C ++ code, using a reference is not only allowed, but it is recommended to use this option.
As an example of illegal use, you can try to pass it in void (*)(TestParameters_t*)
and pass that pointer as a callback to some C code - this is illegal and causes undefined behavior.
source to share
Yes, it works great in C ++.
In general, C is a subset of C ++, but there are exceptions. The usual struct
definition and usage is not one of these exceptions.
Wikipedia does a good job of listing exceptions fully: http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B#Constructs_valid_in_C_but_not_in_C.2B.2B
I would add AG a clause about passing references const
when you write C ++.
I'm assuming you know what extern "C"
prevents the name change that C ++ does, so that anything defined in this scope extern
can also be used in C? If you plan to only use struct
only the code in C ++. I would recommend removing all items extern
. Also note that you no longer need the typedef
or suffix name if you are just in C ++.
In C ++, you can define yours struct
like this:
struct TestParameters {
long p1;
long p2;
long p3;
};
And then use it as a: TestParameters
.
But only does this if you remove C support.
source to share