Mail Archives: djgpp/1997/08/26/19:06:39
[posted and emailed]
Jeff Weeks <pweeks AT execulink DOT com> wrote:
>I'd like to have a function in a struct that I've created. I realise I
>can't just stick a functions in there, so I used a pointer to a
>function. Here's what my struct looks like:
>
>typedef struct {
> VesaInfo card; // information about the video card
> VesaModeInfo mode; // information about the current mode
> int bytes_per_line; // the number of bytes per scanline
> int size; // the size in bytes of the whole screen
> char *address; // the address of actual video memory
> void (*blit)(char *); // a routine to copy a virtual screen to memory
>} Driver;
>
>And then I define an instance and set blit to something:
>
>Driver driver;
>driver.blit = lfb_blit;
>
>But when I try to call the actual function, it crashes. I know the
>lfb_blit() function is not at fault (I've tested it separately), so the
>problem is in calling the function from the struct. I do it as follows:
>
>char *virt = (char *)malloc(640*480*2);
>driver.blit(virt);
Here is a tested example that demonstrates one way to do it:
#include <stdio.h>
typedef struct {
void (*foo)(char *);
} BAR;
BAR bar;
#define foobar (*bar.foo)
void func1(char *);
void func2(char *);
int main(void)
{
bar.foo = func1;
foobar("The first function");
bar.foo = func2;
foobar("The second function");
return 0;
}
void func1(char *s) { printf("func1: %s\n", s); }
void func2(char *s) { printf("func2: %s\n", s); }
/* eof */
Floyd
--
Floyd L. Davidson floyd AT polarnet DOT com
Salcha, Alaska or: floyd AT tanana DOT polarnet DOT com
- Raw text -