编码过程中,需要用到结构体和结构体的指针,而且同时在C和C++的环境下,稍微有点心得,总结如下:
<!--[if !supportLists]-->一. <!--[endif]-->基础代码:
有如下的结构体:
//! structrue for all PH_DATA
typedef struct _PH_DATA
{
INT8U type;//!different type for PH ,for different parameters,such as onepoint ,offsetZ,measurement formula ........
FP32 EVal; //<!< also the meausred mV value,different display
FP32 E0Val;//!< offset value
FP32 sVal; //!< slope value
FP32 sPVal;//!< slope percent value
FP32 returnVal;//!< return the value
INT8U returnStatus;//!< return the status
}S_PH_DATA,*Ptr_S_PH_DATA;
显而易见, S_PH_DATA是一个结构体,而Ptr_S_PH_DATA是一个指向结构体的指针.
<!--[if !supportLists]-->二. <!--[endif]-->结构体的使用方法.
据我所知,在C++下有三种函数参数使用结构体的方法(其实也就是三种向函数传递数值的方式):按值调用(call-by-value),用引用参数按引用调用(call-by-reference reference argument)和用指针参数按引用调用(call-by-reference pointer argument).而标准C是不支持用引用参数按引用调用的.所以如果c和c++混编的情况下,建议使用指针.
三种方法代码分别如下:
<!--[if !supportLists]-->1. <!--[endif]-->按值调用:
int main()
{
S_PH_DATA testPh;
testPh.EVal = 1.0f;
HandleCmd(testPh);
printf(“testPh.returnVal is %f/r/n”, testPh.returnVal);
}
void HandleCmd(S_PH_DATA inPhData)
{
inPhData.returnVal = 1.1f;
}
运行到printf的时候,会报错,提示testPh未初始化,因为按值调用只是传递了参数的一个复本,所以并不会修改参数的值,其实HandleCmd的计算根本没用.
<!--[if !supportLists]-->2. <!--[endif]-->用引用参数按引用调用:
int main()
{
S_PH_DATA testPh;
testPh.EVal = 1.0f;
HandleCmd(&testPh);
printf(“testPh.returnVal is %f/r/n”, testPh.returnVal);
}
void HandleCmd(S_PH_DATA &inPhData)
{
inPhData.returnVal = 1.1f;
}
这个编译通过没问题,而且可以打出正确的值.但是,在C中会编译不通过,C不支持引用.
<!--[if !supportLists]-->3. <!--[endif]-->用指针参数按引用调用:
int main()
{
S_PH_DATA testPh;
testPh.EVal = 1.0f;
HandleCmd(&testPh); //取得参数地址.
printf(“testPh.returnVal is %f/r/n”, testPh.returnVal);
}
void HandleCmd(Ptr_S_PH_DATA inPhData)
{
assert(inPhData!=NULL);
inPhData->returnVal = 1.1f;
}
效果和用引用参数按引用调用一样,c和C++都可以这么用的.但是要注意, 通过assert(inPhData!=NULL)来预防指针跑飞.
转自:http://blog.youkuaiyun.com/lbzhao_28/archive/2008/11/04/3218872.aspx