PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Wed Jul 23, 2008 1:29 pm |
|
|
Here is a demo program that will probably help you. It displays the
following output:
Quote: | Hello World
Hi There
|
Notice the code in main() copies the function pointer from the
structure variable into a temp variable before calling it.
That's a work-around that I found is necessary in CCS.
I haven't been able to call the function by using the struct.element
representation. It has to be copied into a simple function ptr
variable first. This program was tested with PCH vs. 4.076.
Code: |
#include <18F452.h>
#fuses XT,NOWDT,NOPROTECT,BROWNOUT,PUT,NOLVP
#use delay(clock=4000000)
#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7, ERRORS)
char Hello_str[] = {"Hello "};
char World_str[] = {"World\n\r"};
char Hi_str[] = {"Hi "};
char There_str[] = {"There\n\r"};
// This function returns a pointer to a string. The desired
// string is selected by using a parameter of 0 or 1.
char *HelloWorld(int8 strnum)
{
if(strnum == 0)
return(Hello_str);
else
return(World_str);
}
// This function also returns a pointer to a string. The
// desired string is selected by using a parameter of 0 or 1.
char *HiThere(int8 strnum)
{
if(strnum == 0)
return(Hi_str);
else
return(There_str);
}
// Typedef a function pointer.
typedef char* (*_fptr)(int8);
// Create a structure that contains two variables
// and two fuction pointers. Initialize them.
struct
{
int8 value;
int8 my_val;
_fptr fn1;
_fptr fn2;
}My_struct = {0, 0, HelloWorld, HiThere}; // Init values
//====================================
void main()
{
char *string_ptr;
// Create a temp variable to hold a function pointer.
_fptr temp;
temp = My_struct.fn1; // Copy func ptr to temp variable
string_ptr = (*temp)(0); // Call the HelloWorld function
printf(string_ptr); // Display the "Hello" string
string_ptr = (*temp)(1); // Call the HelloWorld function
printf(string_ptr); // Display the "World" string
temp = My_struct.fn2; // Copy func ptr to temp variable
string_ptr = (*temp)(0); // Call the HiThere function
printf(string_ptr); // Display the "Hi" string
string_ptr = (*temp)(1); // Call the HiThere function
printf(string_ptr); // Display the "There" string
while(1);
} |
This program is an expansion of the code that I posted in this thread:
http://www.ccsinfo.com/forum/viewtopic.php?t=33458 |
|