Newsgroups: comp.os.msdos.djgpp,comp.lang.c From: floyd AT icefog DOT polarnet DOT com (Floyd L. Davidson) Subject: Re: Functions in struct's... possible? How? Message-ID: <5tj1tt$fsu@icefog.polarnet.com> Date: 21 Aug 1997 19:43:57 -0800 References: <33FCDA5C DOT 2353659F AT execulink DOT com> Organization: _________ Reply-To: floyd AT polarnet DOT com Lines: 63 To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Precedence: bulk [posted and emailed] Jeff Weeks 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 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