473,796 Members | 2,465 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

OOP in C!

Hi,

I have a feeling that OOP can be done in C also. I have used a
structure to hold member variables and function pointers. The
structure is used as a class to create new 'objects'. But I hit a
problem. How do I access these 'member variables' from the function
that is pointed to by the function pointer in the structure.

I would really appreciate help with this and a code sample will be
wonderful.

Thanks in advance,
Prashanth Ellina
Nov 14 '05
70 2918
On 2004-06-07, E. Robert Tisdale <E.************ **@jpl.nasa.gov > wrote:
Christian Bau wrote:
"Callback function" refers to usage.
"Function pointer" refers to implementation.
Function pointers that are not used as callback functions
are not callback functions.


Please show an example
where a function pointer is *not* used to implement a callback function.


/* -- example.c -- */

static void example_func_im pl(void);
static void example_func_im pl_init(void);

static void (*example_func_ pointer)(void) = example_func_im pl_init;

void example_func(vo id)
{
example_func_po inter();
}

static void example_func_im pl_init(void)
{
/* do some initialization stuff for the first time function is called */
/* ... */

example_func_po inter = example_func_im pl;
example_func_im pl();
}

static void example_func_im pl(void)
{
/* do what the function is supposed to do */
/* ... */
}

-- James
Nov 14 '05 #21
E. Robert Tisdale wrote:

Please show an example
where a function pointer is *not* used to implement a callback function.


A callback function is an example of inversion of control,
a function pointer does not necessarily involve inversion of
control. It seems to me that the line is blurry, but a function
pointer is not necessarily a callback function.

--
Thomas.

Nov 14 '05 #22
Yes, object oriented programming is possible in C. I would recommend going
that route only if a C++ compiler is not available on the platform.

The following article discussess "OOP in C":

http://www.eventhelix.com/RealtimeMa...mming_in_c.htm

Sandeep
--
http://www.EventHelix.com/EventStudio
EventStudio 2.0 - Real-time and Embedded System Design CASE Tool
Nov 14 '05 #23
Christian Bau wrote:
"E. Robert Tisdale" <E.************ **@jpl.nasa.gov > wrote:
Stephen Sprunk wrote:
E. Robert Tisdale wrote:

Please show an example where a function pointer is *not*
used to implement a callback function.

jump tables


Yes, a virtual function table may be implemented as a jump
table. But the function pointers in a jump table point to
callback functions.


Since your little brain doesn't have enough braincells to
understand the difference between a function pointer and a
callback function, giving an example to you would be pointless.


If you are familiar with the long running US comedy 'Cheers', you
may remember the various jokes about usage of 'Cliffs brain'. We
have a Trollsdale serving a very similar function.

--
A: Because it fouls the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?

Nov 14 '05 #24

"Christian Bau" wrote:
"E. Robert Tisdale" wrote:
Stephen Sprunk wrote:
E. Robert Tisdale wrote:

>Please show an example
>where a function pointer is *not* used to implement a
>callback function.

jump tables


Yes, a virtual function table may be implemented as a
jump table. But the function pointers in a jump table
point to callback functions.


Since your little brain doesn't have enough braincells to
understand the difference between a function pointer and a
callback function, giving an example to you would be
pointless.


I don't really understand the vitriol here (nor am I asking for an
explanation for it either), but I've read through this thread a few
times now and my understanding as it stands is this:

The term "callback" is a label given to a function called indirectly
by being dereferenced via a function pointer. As you've said,
"Callback function" refers to usage. There's nothing really special
about a callback function per se; it's all about intent and usage.
Usually, a callback function is written with a specific use in mind,
as in the qsort example you used, but beyond that a callback
function is simply a normal function.

The callback mechanism is implemented through function pointers. In
other words, the callback function itself is not implemented through
function pointers but rather the means of "calling back" the
function is accomplished through function pointers.

So far, so good?

If I'm on track, the question of when function pointers are used in
a non-callback context is an interesting one, at least to me. I
can't think of any off hand, and I'm not sure I understand the "bit
pattern" example given up thread. That's not to say there aren't any
uses of function pointers outside of a callback mechanism, I just
don't know of any.

As far as the difference between virtual functions used in an object
oriented language and callback functions as they are implemented in
C, seems like the underlying mechanics can be similar but that the
term "callback" is really too low-level to be used in an OOL. Other
than that, I don't have much to say.

Nov 14 '05 #25

"Wavemaker" <ja**********@B iteMeHotmail.co m> wrote in

I don't really understand the vitriol here (nor am I asking for an
explanation for it either), but I've read through this thread a few
times now and my understanding as it stands is this:
We'll spare you that. Some people should be more careful in responding to E.
Robert Tisdale.
The term "callback" is a label given to a function called indirectly
by being dereferenced via a function pointer.
And also passed to a lower level function. Eg qsort() takes a callback
function.
In C it is impossible to place restrictions on functions (eg insist that
they be leaf functions, ban them from performing IO, insist they be pure
functions, etc).
If I'm on track, the question of when function pointers are used
in a non-callback context is an interesting one, at least to me. I
can't think of any off hand, and I'm not sure I understand the "bit
pattern" example given up thread. That's not to say there aren't
any uses of function pointers outside of a callback mechanism, I
just don't know of any.
Generally you would use a function pointer to abstract some of the logic.
For instance qsort() can sort any set of structures because the comparison
is not hard-coded. If you are implementing a hash table you might want
function pointers for retrieving keys, maybe implementing the hash function
itself.
There are a few cases.
let's say we are debugging and we want to know where the compiler is putting
our function in memory.

void print_fptr( void (*fptr)(void))
{
unsigned char pattern[sizeof fptr];
int i;

memcpy(pattern, &fptr, sizeof fptr);
for(i=0;i<sizeo f fptr;i++)
printf("%2X", pattern[i]);
}

Another case might be if we are implementing the "prisoner's dilemma"
tournament. This is a competition in which one may either co-operate or
defect, mutual co-operation gives a bigger payoff than mutual defection, but
defecting when partner co-operates gives him nothing at all and you the
biggest payoff of all.

An obvious way to do it would be to encode strategies as C functions, then
have a big population of function pointers, which find partners at random.
As strategies succeed they get more copies in the pool - more function
pointers, that is.

In this program, though you are using function pointers, you are not passing
them to a subroutine so they are not "callback functions".
As far as the difference between virtual functions used in an
object oriented language and callback functions as they are
implemented in C, seems like the underlying mechanics can be
similar but that the term "callback" is really too low-level to be
used in an OOL.

Term "callback function" makes sense in terms of a program which is
basically a hard-coded tree of subroutines, but in which one or two function
pointers are passed dynamically.
In an OO design that makes heavy use of virtual functions the term stops
being useful since so many functions are called through pointers, so we use
the term "virtual member functions" instead. English usage is flexible so we
don't need to fuss too much if someone refers to these as "callback
functions".
Nov 14 '05 #26
In article <news:d-*************** *****@comcast.c om>
Wavemaker <ja**********@B iteMeHotmail.co m> writes:
The term "callback" is a label given to a function called indirectly
by being dereferenced via a function pointer. ...
That is one possible definition of the term "callback function",
but I contend it is not a very good one.
As [someone else] said, "Callback function" refers to usage.
This is a better definition. It is still not all that solid,
though.

A google search suggests that there is no single, fixed definition
in computing. Microsoft have two separate definitions, one for
their Windows API and one for IIS. Erlang defines a callback
function as a (particular kind of) function in a callback module.
All these definitions share a common "flavor", though, and they
all fit at least reasonably well under the "usage" label. I think
we can refine this a bit though, by splitting tasks among particular
"entities", and referring back to the English-language meaning of
"I'll call you back".

Suppose a program is split into two or more "algorithmi c entities",
where the responsibility for some particular task is delegated to
some sub-entity. For instance, we might have an application that
interacts with a user, talks to a database, and runs a printer,
all at various times.

Suppose the user code calls the database software, and while that
is doing its job, it encounters a database problem and needs to do
some quick interaction with the user (while still being "mostly
database-y"). It might use a "callback" into the user-interface
code to achieve this.

Later, if the database code decides to run the printer, and the
code running the printer runs into a problem and needs information
from the database (while still being "mostly printer-y"), it might
use a "callback" into the database code. If the answer is "this
requires user interaction", but the database and printer code is
not being called *by* the user-interaction code, then a call from
the database or printer code into the user-interaction code is just
a "call", not a "call back".

There is still a lot of "wool" in this attempt to "define by example",
so let me try a more formal specification. This is just my attempt,
not any sort of "official" definition for a callback function:

A function is labeled "callback" when it is "called back" by
a separate body of code that is called to perform some specific
task. That is, code-group A calls code-group B, and code-group
B does most of the work, but occasionally needs processing by
code-group A. If that extra processing is supplied by having
code-group B call a specified function within code-group A,
the designated function in A is a "callback".
There's nothing really special about a callback function per se;
it's all about intent and usage. Usually, a callback function is
written with a specific use in mind, as in the qsort example you
used, but beyond that a callback function is simply a normal function.
Right.
The callback mechanism is implemented through function pointers.
Not necessarily.

This *is* a useful mechanism, but not the only possible one, even
in C, and in other languages only the alternative mechanisms might
be available.

Let me use a simple quicksort function again as an example. This
quicksort will use the same calling sequence as C's qsort(), except
that the comparison function pointer is omitted. That is, instead
of:

void qsort(void *base, size_t nel, size_t width,
int (*compar)(const void *, const void *));

we have (nb, I just typed this in without testing it, no guarantee
it is correct, and it is not optimized in any way):

void quicksort(void *base, size_t nel, size_t width) {
extern int qcompare(const void *, const void *);
unsigned char *b, *pivot;
unsigned char *l, *r;
size_t i, j, half;

if (nel < 2) /* empty or 1 element => already sorted */
return;
b = base;
i = 0;
j = nel - 1;
/* select "middle" item as pivot, rounding up "just because" */
half = (j + 1) / 2;
pivot = base + half;
partition:
if (i <= j) {
l = base + i * width; /* left-side item */
if (qcompare(l, pivot) < 0) {
i++;
goto partition;
}
r = base + j * width; /* right-side item */
if (qcompare(r, pivot) >= 0) {
j--; /* can get j<i here */
goto partition;
}
if (i < j) {
/* qmemswap saves item l, copies r to l, copies saved to r */
qmemswap(l, r, width);
goto partition;
}
}
/*
* now everything from [0..half) < pivot and everything from
* (half..nel) is >= pivot, and of course pivot == pivot.
* The second interval might be empty.
*/
quicksort(base, half, width);
if (nel - 1 > half)
quicksort(pivot + width, nel - half - 1, width);
}

Here quicksort() "calls back" into whatever called it by calling
the function qcompare() *using the name qcompare*.

To use this version of quicksort, instead of the (no doubt superior)
C library qsort(), you must name your function "qcompare". You
get only one comparison function per C program. But qcompare() is
still a callback function, *even though it is called directly*
(rather than via a pointer).
In other words, the callback function itself is not implemented through
function pointers but rather the means of "calling back" the
function is accomplished through function pointers.
Or, by name -- but using a pointer is "better", because in this
case, it allows us to call qsort() from any number of places, and
use different functions, not just qcompare(), to compare elements.
If I'm on track, the question of when function pointers are used in
a non-callback context is an interesting one, at least to me.


You might find a good example in a state-machine, such as this
skeleton that works with a hardware device:

struct state {
struct state (*next)(struct state);
... other elements if needed ...
};

struct state start(struct state);
struct state stop(struct state);
...
void run_state_machi ne(void) {
struct state s = { start };
do {
wait_for_hardwa re_to_be_ready( );
s = s.next(s);
} while (s.next != stop);
}
...
struct state start(struct state x) {
if (some_hardware_ switch)
x.next = s1;
else
x.next = s2;
return x;
}
...

These do not really qualify as "callbacks" because the entire
machine is all one body of code. Functions start(), s1(), s2(),
s3(), ..., stop() are all provided as a single package, and the
"driver" function -- run_state_machi ne() -- is permanently attached
to the same package, by virtue of waiting for the hardware in
question before each step.

Of course, you could "re-divide" the task here, so that the state
machine is separate from the hardware-interation. If you did that,
each state-handler *would* suddenly qualify for the "callback"
label. But this is as it should be: if you restructure the code
and move responsibilitie s around, it becomes different code, using
the same mechanisms for different purposes, so it may well deserve
different labels.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #27
"Mike Wahler" <mk******@mkwah ler.net> wrote in message news:<VN******* ***********@new sread1.news.pas .earthlink.net> ...
#include <stdio.h>

struct S
{
int member;
void (*fp)(struct S *);
};

void func(struct S *param)
{
printf("%d\n", param->member);
}

int main()
{
struct S object = {42, func};
func(&object); /* prints 42 */

shouldn't the above line be,
object.fp(&obje ct);
?

return 0;
}

-Mike

Thanks in advance,
Prashanth Ellina

Nov 14 '05 #28
Prashanth Ellina wrote:
Mike Wahler wrote:
#include <stdio.h>

struct S {
int member;
void (*fp)(struct S *);
};

void func(struct S *param) {
printf("%d\n", param->member);
}

int main() {
struct S object = {42, func};
func(&object); /* prints 42 */


shouldn't the above line be,

object.fp(&obje ct);

?


Yes.
return 0;
}

Nov 14 '05 #29
"Chris Torek" <no****@torek.n et> wrote in message
news:ca******** *@news4.newsguy .com...
There is still a lot of "wool" in this attempt to "define by example",
so let me try a more formal specification. This is just my attempt,
not any sort of "official" definition for a callback function:

A function is labeled "callback" when it is "called back" by
a separate body of code that is called to perform some specific
task. That is, code-group A calls code-group B, and code-group
B does most of the work, but occasionally needs processing by
code-group A. If that extra processing is supplied by having
code-group B call a specified function within code-group A,
the designated function in A is a "callback".


This is nearly identical to the loose definition I've been operating under.

One thing I'd add is that, while not required, code-group B was usually
written, translated, and installed long before code-group A was even
conceived. qsort() is obviously a perfect example from the standard
library, but in my experience GUI toolkits are the more common (and less
trivial) users of callback functions.

S

--
Stephen Sprunk "Stupid people surround themselves with smart
CCIE #3723 people. Smart people surround themselves with
K5SSS smart people who disagree with them." --Aaron Sorkin

Nov 14 '05 #30

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
11248
by: William C. White | last post by:
Does anyone know of a way to use PHP /w Authorize.net AIM without using cURL? Our website is hosted on a shared drive and the webhost company doesn't installed additional software (such as cURL) on the server because of that. Our site will have an SSL certificate next week, so I would like to use AIM instead of SIM, however, I don't know how to send data via POST over https and recieve data from the Authorize.net server over an https...
2
5844
by: Albert Ahtenberg | last post by:
Hello, I don't know if it is only me but I was sure that header("Location:url") redirects the browser instantly to URL, or at least stops the execution of the code. But appearantely it continues to execute the code until the browser send his reply to the header instruction. So an exit(); after each redirection won't hurt at all
3
23040
by: James | last post by:
Hi, I have a form with 2 fields. 'A' 'B' The user completes one of the fields and the form is submitted. On the results page I want to run a query, but this will change subject to which field is completed.
0
8497
by: Ollivier Robert | last post by:
Hello, I'm trying to link PHP with Oracle 9.2.0/OCI8 with gcc 3.2.3 on a Solaris9 system. The link succeeds but everytime I try to run php, I get a SEGV from inside the libcnltsh.so library. 354 roberto@ausone:Build/php-4.3.2> ldd /opt/php4/bin/php libsablot.so.0 => /usr/local/lib/libsablot.so.0 libstdc++.so.5 => /usr/local/lib/libstdc++.so.5 libm.so.1 => /usr/lib/libm.so.1
1
8611
by: Richard Galli | last post by:
I want viewers to compare state laws on a single subject. Imagine a three-column table with a drop-down box on the top. A viewer selects a state from the list, and that state's text fills the column below. The viewer can select states from the drop down lists above the other two columns as well. If the viewer selects only one, only one column fills. If the viewer selects two states, two columns fill. Etc. I could, if appropriate, have...
4
18307
by: Albert Ahtenberg | last post by:
Hello, I have two questions. 1. When the user presses the back button and returns to a form he filled the form is reseted. How do I leave there the values he inserted? 2. When the user comes back to a page where he had a submitted POST data the browser keeps telling that the data has expired and asks if repost. How to avoid that? I tried registering all POST and GET vars as SESSION vars but
1
6870
by: inderjit S Gabrie | last post by:
Hi all Here is the scenerio ...is it possibly to do this... i am getting valid course dates output on to a web which i have designed ....all is okay so far , look at the following web url http://www.mis.gla.ac.uk/biquery/training/ but each of the courses held have maximum of 8 people that could be
2
31445
by: Jack | last post by:
Hi All, What is the PHP equivilent of Oracle bind variables in a SQL statement, e.g. select x from y where z=:parameter Which in asp/jsp would be followed by some statements to bind a value to :parameter I dont like the idea of making the SQL statement on the fly without binding parameters as I dont want a highly polluted SQL cache.
3
23603
by: Sandwick | last post by:
I am trying to change the size of a drawing so they are all 3x3. the script below is what i was trying to use to cut it in half ... I get errors. I can display the normal picture but not the results of the picture half the size. The PHP I have installed support 1.62 or higher. And all I would like to do is take and image and make it fit a 3x3. Any suggestions to where I should read or look would be appreciated.
0
9680
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10230
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10174
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10012
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6788
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5442
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5575
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3731
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2926
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.