I'm trying to recreate an encapsulation principle in ANSI-C for educational purposes. What I essentially did was making some structure in .c file:
struct _private
{
unsigned char SizeInBytes;
unsigned char* matrix;
struct Stack* S;
unsigned char ByteX;
};
which represented variables I wanted to be unseen. Then in .h file inside the struct (class) I created an opaque pointer:
struct Maze
{
void* _private;
};
which I assign later in constructor function like this:
void* Maze_ctor(void* self, va_list *ap)
{
struct Maze* this = self;
this->DimX = va_arg(*ap, unsigned char);
this->DimY = va_arg(*ap, unsigned char);
this->_private = &(struct _private) // passing address of struct to void*
{
.SizeInBytes = this->DimX*this->DimY >> 1,
.S = new(Stack),
.ByteX = this->DimX % 8 > 0 ? this->DimX / 8 + 1 : this->DimX / 8
};
//
private.matrix = (unsigned char*)malloc(private.ByteX*this->DimY);
S = new(Stack); // this in my new() and it works similar to C++ new
for (int i = 0; i < private.ByteX*this->DimY; i++)
*(private.matrix + i) = 0;
}
At this point everything works fine, but then I'm trying to call the Next() method:
int Next(void* self, ...)
{
struct Maze* this = self;
struct _private *r = this->_private;
short t;
toBinary(this); // after this point the struct private breaks
}
the prototype of toBinary() is:
void toBinary(const void* self)
{
// somehow char local is defined and equals to 204??
struct Maze *this = self;
struct _private *r = this->_private;
unsigned char local; // right after this point SizeInBytes equals to 204!
...
}
the question is: how to fix this problem. Using C++ is prohibited! for the interested ones: here is new()
void* new(const void* _class,...)
{
const struct Class* class = _class; // we need to convert pointer from void* to class* safely
void *p = calloc(1, class->size); // allocation of memory for class .using size param
assert(p); // if Null -> throw an error
*(const struct Class**)p = class; // safe assignment of class pointer to (value) of p, to have memory and built in funcs
if (class->ctor) // if has constructor with some dynal in it, execute with varargs on its input
{
va_list ap;
va_start(ap, _class); //
p = class->ctor(p, &ap); // pass arguments as a list of pointers.
va_end(ap);
}
return p; //returns a pointer to class pointer (weird but worx)
}
As pointed out in the comment, the problem is that you created a local object and assign it to a pointer this
. Outside that function, the value of this
is not valid.
You code,
void* Maze_ctor(void* self, va_list *ap)
{
//....
// this creates a temporary object and will be destroyed after Maz_ctor returns.
this->_private = &(struct _private) // passing address of struct to void*
{
.SizeInBytes = this->DimX*this->DimY >> 1,
.S = new(Stack),
.ByteX = this->DimX % 8 > 0 ? this->DimX / 8 + 1 : this->DimX / 8
};
// ---
}