www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/01/28/06:20:43

Date: Wed, 28 Jan 1998 13:20:41 +0200 (IST)
From: Eli Zaretskii <eliz AT is DOT elta DOT co DOT il>
To: Vic <tudor AT cam DOT org>
cc: djgpp AT delorie DOT com
Subject: Re: HELP: accessing astructure members via VOID pointer??
In-Reply-To: <34CE8F55.1C12@cam.org>
Message-ID: <Pine.SUN.3.91.980128132022.3916L-100000@is>
MIME-Version: 1.0

On Tue, 27 Jan 1998, Vic wrote:

> > BTW, why are you trying to do something so strange? :-)
> > Isn't the usual way enough  (I mean ((struct foo *)bar)->x = 55) ? :-)
> Because I'm trying to do a scripting language for a game engine. At
> compile time it's easy to say p->x, but at run time I just have a chunk
> of memory and no ideea about the member's types,names etc.

You might benefit from more efficient help if you tell more about what
you are trying to accomplish, and what are the constraints that the
solution must meet.  Since you didn't tell much, the following may or
may not be a solution.

One possible way of achieving your goal might be to have the names of
the struct fields and their offsets available, and then dereference
the addresses in the usual way.  Consider the following fragment:

    #include <stddef.h>  /* that's where `offsetof' is defined */
    ...
    struct foo {
      int foo_int;
      double foo_dbl;
      char foo_char[FOO_CHAR_SIZE];
      ...
    };

    struct struct_data {
      char  *name;
      off_t offset;
    } foo_data[] = {
      {"foo_int", offsetof(foo, foo_int)},
      {"foo_dbl", offsetof(foo, foo_dbl)},
      {"foo_char", offsetof(foo, foo_char)}
      ...
    };

Given this setup, you can at runtime use the following way of setting
e.g. foo.foo_int to a given value:

     void *structure;  /* a pointer to a struct foo variable */

     if (strcmp(name, foo_data[0].name) == 0)
	*((int *)((char *)structure + foo_data[0].offset) = value;

where `name' and `value' come from the user or the application which
know nothing about the data structures used by the engine.  For
example, a user might type "foo_int = 3" which you then parse to get
the name and the value.

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019