Suppose I have a structure S containing a function pointer. Now we want this function to be called only by the structure containing pointer only.Not from main directly. How can we design a scheme like that any ideas ??
You could have some initialisation function that sets up p to point to a (file) static function. That way, p would point to the right function and the funtion would be otherwise inaccessible to the rest of the program.
In my eyes, this is simply not possible in C. In C++ you would just make the function pointer private, but since struct fields are all public, I see no way of hiding it.
Data hiding in C is typically done with use of a void pointer. This is effectly what FILE and similar structs do. You never access any FILE members directly (you can't). Instead you call fopen/fread/whatever, and those are what actually access the members.
It's accomplished with something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13
// mystruct.h
typedefstruct
{
void* privatedata;
} MyStruct;
// Creating / Destruction
MyStruct* MyStruct_Create();
void MyStruct_Destroy(MyStruct* p);
// a function that uses MyStruct:
void MyStruct_Foo(MyStruct* p);
// mystruct.c
#include "mystruct.h"
typedefstruct
{
int foo; // actual data members of MyStruct
} MyStruct_Data;
// create a MyStruct
MyStruct* MyStruct_Create()
{
MyStruct* p = malloc(sizeof(MyStruct));
p->privatedata = malloc(sizeof(MyStruct_Data));
return p;
}
// destroy a MyStruct
void MyStruct_Destroy(MyStruct* p)
{
free(p->privatedata);
free(p);
}
// a function that uses MyStruct
void MyStruct_Foo(MyStruct* p)
{
MyStruct_Data* dat = p->privatedata;
dat->foo = whatever;
}
Since the actual data members are in the c file and not in the h file... only functions in the c file are able to access them. Therefore code outside of MyStruct can only interface with it through the provided functions.