J
Jason Curl
Hello,
I often try to implement datahiding as best as I can in C but the method
I use is typecasts. I've read in numerous posts of this newsgroup that
any typecasts (while in some cases is valid), is usually shunned upon.
I've not listed the missing headers and I've not done any error checking
for brevity in the example below. Of course one would normally check for
NULL pointers as results of malloc() and as inputs.
Is this generally acceptable, or are there better ways of implementing
datahiding (without the potential of making silly errors due to typecasts).
I try and avoid "private" headers, because they're still headers that
must be distributed and that someone can see and modify internal parameters.
mydt.h
------
typedef void mydt_handle;
mydt_handle *initdt(int value);
void termdt(mydt_handle *handle);
mydt.c
------
typedef struct mydt_handle_s {
int value;
} mydt_handle_t;
mydt_handle *initdt(int value)
{
mydt_handle_t *h;
h = malloc(sizeof(mydt_handle_t));
h->value = value;
return (mydt_handle *)h;
}
void termdt(mydt_handle *handle)
{
mydt_handle_t *h;
h = (mydt_handle_t *)handle;
printf("Value is %d\n", h->value);
free(h);
}
I often try to implement datahiding as best as I can in C but the method
I use is typecasts. I've read in numerous posts of this newsgroup that
any typecasts (while in some cases is valid), is usually shunned upon.
I've not listed the missing headers and I've not done any error checking
for brevity in the example below. Of course one would normally check for
NULL pointers as results of malloc() and as inputs.
Is this generally acceptable, or are there better ways of implementing
datahiding (without the potential of making silly errors due to typecasts).
I try and avoid "private" headers, because they're still headers that
must be distributed and that someone can see and modify internal parameters.
mydt.h
------
typedef void mydt_handle;
mydt_handle *initdt(int value);
void termdt(mydt_handle *handle);
mydt.c
------
typedef struct mydt_handle_s {
int value;
} mydt_handle_t;
mydt_handle *initdt(int value)
{
mydt_handle_t *h;
h = malloc(sizeof(mydt_handle_t));
h->value = value;
return (mydt_handle *)h;
}
void termdt(mydt_handle *handle)
{
mydt_handle_t *h;
h = (mydt_handle_t *)handle;
printf("Value is %d\n", h->value);
free(h);
}