S
sofeng
I'm not sure if "data hiding" is the correct term, but I'm trying to
emulate this object-oriented technique. I know C++ probably provides
much more than my example, but I'd just like some feedback to find out
if I've done anything wrong. Also, I am working on this for an
embedded environment, so if there are great inefficiencies with this
code, I'd like to know that also. I realize there is overhead with
using an "accessor" function.
I'm trying to:
1.) "hide" data (variables declared as static at file scope) within a
file (algorithm.c)
2.) manipulate the data using an algorithm function (Algorithm())
3.) provide external access to the data using an "accessor" function
(GetAlgorithmData())
Here is my code:
main.c:
#include <stdio.h>
#include "algorithm.h"
int main(void)
{
const ALGORITHM_DATA *alg_ptr;
Algorithm();
GetAlgorithmData(&alg_ptr);
/*alg_ptr->data1 = 99.9;*/ /* This is not allowed */
printf("%f\n", alg_ptr->data1);
printf("%f\n", alg_ptr->data2);
printf("%f\n", alg_ptr->data3);
return 0;
}
algorithm.c:
#include "algorithm.h"
static ALGORITHM_DATA alg;
void GetAlgorithmData(const ALGORITHM_DATA **out)
{
*out = &alg;
}
void Algorithm(void)
{
alg.data1 = 1.0;
alg.data2 = 2.0;
alg.data2 = 3.0;
}
algorithm.h:
#ifndef ALGORITHM_H_
#define ALGORITHM_H_
typedef struct {
double data1;
double data2;
double data3;
} ALGORITHM_DATA;
void GetAlgorithmData(const ALGORITHM_DATA **out);
void Algorithm(void);
#endif /*ALGORITHM_H_*/
emulate this object-oriented technique. I know C++ probably provides
much more than my example, but I'd just like some feedback to find out
if I've done anything wrong. Also, I am working on this for an
embedded environment, so if there are great inefficiencies with this
code, I'd like to know that also. I realize there is overhead with
using an "accessor" function.
I'm trying to:
1.) "hide" data (variables declared as static at file scope) within a
file (algorithm.c)
2.) manipulate the data using an algorithm function (Algorithm())
3.) provide external access to the data using an "accessor" function
(GetAlgorithmData())
Here is my code:
main.c:
#include <stdio.h>
#include "algorithm.h"
int main(void)
{
const ALGORITHM_DATA *alg_ptr;
Algorithm();
GetAlgorithmData(&alg_ptr);
/*alg_ptr->data1 = 99.9;*/ /* This is not allowed */
printf("%f\n", alg_ptr->data1);
printf("%f\n", alg_ptr->data2);
printf("%f\n", alg_ptr->data3);
return 0;
}
algorithm.c:
#include "algorithm.h"
static ALGORITHM_DATA alg;
void GetAlgorithmData(const ALGORITHM_DATA **out)
{
*out = &alg;
}
void Algorithm(void)
{
alg.data1 = 1.0;
alg.data2 = 2.0;
alg.data2 = 3.0;
}
algorithm.h:
#ifndef ALGORITHM_H_
#define ALGORITHM_H_
typedef struct {
double data1;
double data2;
double data3;
} ALGORITHM_DATA;
void GetAlgorithmData(const ALGORITHM_DATA **out);
void Algorithm(void);
#endif /*ALGORITHM_H_*/