How do I create a function in my library for passing user callback function

A

Angus

Hello

I am writing a library which will write data to a user defined callback
function. The function the user of my library will supply is:

int (*callbackfunction)(const char*);

In my libary do I create a function where user passes this callback
function? How would I define the function?

I tried this

callbackfunction clientfunction;

void SpecifyCallbackfunction(cbFunction cbFn)
{
clientfunction = cbFn;
}

Then called like this:
clientfunction(sz); // sz is a C-string.

But program crashes with access violation when attempt to call
clientfunction



What am I doing wrong?
 
I

Ian Collins

Angus said:
Hello

I am writing a library which will write data to a user defined callback
function. The function the user of my library will supply is:

int (*callbackfunction)(const char*);

In my libary do I create a function where user passes this callback
function? How would I define the function?

I tried this

callbackfunction clientfunction;

void SpecifyCallbackfunction(cbFunction cbFn)
{
clientfunction = cbFn;
}

Then called like this:
clientfunction(sz); // sz is a C-string.
You should be passing the address of the function, not a string.

int f( const char* );

clientfunction( f );
 
I

Ian Collins

Richard said:
Ian Collins said:


I doubt it. Since clientfunction is an instance of callbackfunction (and
presumably the definition of callbackfunction, above, is supposed to be a
typedef), it takes a const char *, not an int(*)(const char *).
OK, I promise never to post pre-caffeine ever again!

I read the OP as passing a string to SpecifyCallbackfunction.
 
B

Ben Bacarisse

Angus said:
I am writing a library which will write data to a user defined callback
function. The function the user of my library will supply is:

int (*callbackfunction)(const char*);

In my libary do I create a function where user passes this callback
function? How would I define the function?

I tried this

callbackfunction clientfunction;

This won't compile. I suspect you have a typedef that you are not
showing us!

But program crashes with access violation when attempt to call
clientfunction

What am I doing wrong?

Try to post a short, compilable, example of the problem. The outline
you posted is sound, the error is in the detail (and is somewhere
else).
 
B

Bill Reid

Hello

I am writing a library which will write data to a user defined callback
function. The function the user of my library will supply is:

int (*callbackfunction)(const char*);

In my libary do I create a function where user passes this callback
function? How would I define the function?

I tried this

callbackfunction clientfunction;

void SpecifyCallbackfunction(cbFunction cbFn)
{
clientfunction = cbFn;
}

Then called like this:
clientfunction(sz); // sz is a C-string.

But program crashes with access violation when attempt to call
clientfunction

What am I doing wrong?

Well, just about everything, and most pertinently, asking a question
here, the land of the technically-incompetent trolls...but here's how
you do it:

In the header file for your library, declare the function as follows:

extern void my_library_function(int (*)(const char*));

(Note: as somebody may tell you, "extern" is a redundant
linkage specifier for function declarations, but I use it anyway
and therefore you should too!)

Now write your library function that takes the callback as
a parameter in the source file for your library:

void my_library_function(int my_callback_function(const char*)) {
int my_callback_return;
char *my_string;

... /* generic stuff done here, probably "build up" my_string */

my_callback_return=my_callback_function(my_string);

... /* more generic stuff maybe, maybe check my_callback_return */
}

Now, for any source file that you want to use that generic
my_library_function(), you can call it by first #include'ing the
library header file, then defining a specific callback function that
matches the declaration in the header file:

int my_specific_function(const char* my_string) {

... /* do something with string, probably print it, right? */
}

Then you can call your library function with the callback anywhere
in your source file, as well as any other functions that you have defined
that match the callback signature:

void my_function(void) {

... /* stuff happens here, whatever, maybe nothing, who knows */

my_library_function(my_specific_function);

... /* and whatever else */
}

And that's "all" there is to it...not that bad once you get the hang of
it, just follow the pattern above, sometimes you have to really "think"
about what the perfect "signature" will be for all the various callbacks
you want for a generic library function, what all data you need to
pass for all possible conditions...
 
B

Bill Reid

Richard Heathfield said:
Bill Reid said:


When you make a claim like that, you should back it up with working code.
You didn't. A conforming implementation *must* diagnose, and *may* refuse
to translate, your code.

Well, I didn't really write any code, you insane troll, so I guess
you're "right" again, as always...
Your track record of ignoring or even railing against those who notify you
of your mistakes gives me little or no hope that you'll pay any attention
to this, but the OP will at least have fair warning of the kind of
"competence" to which you are exposing him.

Well, no, I couldn't help but notice that you didn't specify any
actual problems with what I posted, so how would he know what's
wrong with it? Believe me, for his sake, you should let HIM know,
and let ALL of us know, including me, so we can all benefit from
your tremendous "wisdom"...I'd be the first to admit that I make
a LOT of mistakes, have made many here, and there may be
errors or omissions in my post, and I'd genuinely like to be
"set straight", but somehow I think you're just blowin' troll
smoke again, as usual...

So if you got anything of substance, post it; I'm not saying it
would be a first, but along the lines of a rarity...
 
N

Nick Keighley

what is cbFunction?
Well, just about everything, and most pertinently, asking a question
here, the land of the technically-incompetent trolls...but here's how
you do it:

before making remarks like that you should make *really*
sure you havn't made any foolish errors in your code...

Oh, sorry I forgot you didn't post any code!


In the header file for your library, declare the function as follows:

extern void my_library_function(int (*)(const char*));

(Note: as somebody may tell you, "extern" is a redundant
linkage specifier for function declarations, but I use it anyway
and therefore you should too!)

a substantial body of people don't, so consider missing it out.


Now write your library function that takes the callback as
a parameter in the source file for your library:

void my_library_function(int my_callback_function(const char*)) {
    int my_callback_return;
    char *my_string;

    ... /* generic stuff done here, probably "build up" my_string  */

    my_callback_return=my_callback_function(my_string);

    ... /* more generic stuff maybe, maybe check my_callback_return  */
    }

Now, for any source file that you want to use that generic
my_library_function(), you can call it by first #include'ing the
library header file, then defining a specific callback function that
matches the declaration in the header file:

int my_specific_function(const char* my_string) {

    ... /* do something with string, probably print it, right?  */
    }

Then you can call your library function with the callback anywhere
in your source file, as well as any other functions that you have defined
that match the callback signature:

void my_function(void) {

    ... /* stuff happens here, whatever, maybe nothing, who knows  */

    my_library_function(my_specific_function);

    ... /* and whatever else  */
    }

And that's "all" there is to it...not that bad once you get the hang of
it, just follow the pattern above,

no! don't follow the pattern above!
sometimes you have to really "think"
about what the perfect "signature" will be for all the various callbacks
you want for a generic library function, what all data you need to
pass for all possible conditions...

no not at all.

Ok. Here's a more compact form of your code with a driver added.


/***********/
/* the code that Bill Reid didn't write */

extern void my_library_function (int (*)(const char*));

void my_library_function(int my_callback_function(const char*)) /*
<--- error */
{
int my_callback_return;
char *my_string = "";
my_callback_return=my_callback_function (my_string);
}

int my_specific_function (const char* my_string)
{
return 0;
}

/* driver added by me */
int main (void)
{
my_library_function (my_specific_function);
return 0;
}
/**********/

and my compiler does this

Compiling...
reid.c
C:\bin\reid.c(6) : warning C4028: formal parameter 1 different from
declaration

So let's try this pattern:-

/* in the header */
typedef int (*Callback)(const char*);
void my_library_function (Callback);


/* in the library */
void my_library_function (Callback my_callback_function)
{
int my_callback_return;
char *my_string = "";
my_callback_return = my_callback_function (my_string);
}


/* in the caller's code */
int my_specific_function (const char* my_string)
{
return 0;
}

/* driver added by me */
int main (void)
{
my_library_function (my_specific_function);
return 0;
}


the typedef makes life *much* easier.

So how to construct the typedef?

Suppose the callback is going to look something like this
int f1 (int x)

put a typedef in front of it and change the name
to your convention for types (I start a typename
with an uppercase letter)
typedef int F1 (int x);

put a * in front of the function name and bracket the name
and the *.
typedef int (*F1) (int x);

remove the argument names if you like.
typedef int (*F1) (int);

You can then use this wherever you need the function
pointer.

A slightly more complicated example
char *f2 (int x, double x, F1 callback);
typedef char* (*F2) (int, double, F1);

You even return function pointers
F1 setCB (F1 new_call);
typedef F1 (*SetCB) (F1);


Some people prefer to typedef the function then the
pointerness is not hidden.

typedef int F1 (int);
typedef char* F2 (int, double, F1*);

And now I'm guilty of Reid's syndrome, I havn't
compiled this. But I did compile the pattern
I recommend (and use).


--
Nick Keighley

As I recall, OSI dealt with TCP/IP by just admitting it into the spec
as a variation of existing levels. This is akin to dealing with an
Alien face hugger by allowing it to implant its embryo in your body.
 
N

Nick Keighley

Bill Reid said:

oh the irony...


Here is the code you claim you didn't really write, which I've copied
verbatim from your article.

<snip code-like stuff>


Note that my observation about failure to compile does not relate to
obvious "more stuff goes here" conventions such as an occasional ellipsis.



No point. You never listen anyway.


Since it doesn't compile, he'll find out pretty quickly that it *is* wrong.
As to *why* it's wrong, that's easy. It was written by someone who doesn't
understand C very well.


After you.

perhaps, Richard, if you tried to be just a little less gnomic...
Perhaps, even, point out the error :)

Who remembers the Campaign Againt Grumpiness in c.l.c.?


--
Nick Keighley

If cosmology reveals anything about God, it is that He has
an inordinate fondness for empty space and non-baryonic dark
matter.
Sverker Johansson (talk.origins)
 
Y

ymuntyan

what is cbFunction?



before making remarks like that you should make *really*
sure you havn't made any foolish errors in your code...

Oh, sorry I forgot you didn't post any code!




a substantial body of people don't, so consider missing it out.













no! don't follow the pattern above!


no not at all.

Ok. Here's a more compact form of your code with a driver added.

/***********/
/* the code that Bill Reid didn't write */

extern void my_library_function (int (*)(const char*));

void my_library_function(int my_callback_function(const char*)) /*
<--- error */
{
int my_callback_return;
char *my_string = "";
my_callback_return=my_callback_function (my_string);

}

int my_specific_function (const char* my_string)
{
return 0;

}

/* driver added by me */
int main (void)
{
my_library_function (my_specific_function);
return 0;}

/**********/

and my compiler does this

Compiling...
reid.c
C:\bin\reid.c(6) : warning C4028: formal parameter 1 different from
declaration

Is it the error you mentioned? What does it warn about?
Parameter is declared as a function, that's adjusted to
the pointer to a function. What exactly is wrong?

Yevgen
 
B

Ben Bacarisse

Bill Reid said:
Well, just about everything, and most pertinently, asking a question
here, the land of the technically-incompetent trolls...but here's how
you do it:

Posting incorrect syntax won't help the OP. In fact, there is some
evidence that the OP knows the correct syntax for what they are doing
since the problem they report is a run time one. Only an example of
their actual code will help diagnose what they are doing wrong.
 
N

Nick Keighley

Is it the error you mentioned?

is *what* the error I mentioned? The error above occurs on
the line I indicated.

What does it warn about?

I have this trouble when people ask me to explain syntax errors.
To me (maybe I've been at this too long) they seem self explanatory
(maybe one day I'll say the same about a three page C++
template diagnostic (but not yet)).

Well it warns that the formal parameters does not
match the declaration. It even tells you which parameter (paramter 1).
Which
is nice of it but not very helpful as it only has one parameter.

The formal parameter appears in the definition
void my_library_function(int my_callback_function(const char*))

so the formal parameter is
int my_callback_function(const char*))

which is a function. This doesn't make much sense to me.
I'm surprised the compiler didn't get more upset.

The declaration is:
extern void my_library_function (int (*)(const char*));

so the parameter is
int (*)(const char*)

Formal is a ptr-to-function-taking-const-char*-and-returning-int

So what parameter is a function declaration and the other
is a function pointer. They don't match.

Parameter is declared as a function, that's adjusted to
the pointer to a function. What exactly is wrong?

is it?
 
B

Bill Reid

Wouldn't you know it, this tool posts from Google(TM) Groups...

HEY, FOOL, IF YOU'RE GONNA BE SUCH AN IDIOT AS TO
POST FROM THE SCOURGE OF USENET, AT LEAST LEARN
HOW TO DO IT SO YOUR POSTS ARE QUOTED PROPERLY!!!

TIA!!! (but really, not holding my breath waiting for him to learn
how to post to Usenet...that's too "technical")


PKB. But let's see how this develops...just don't get all pissy
if it doesn't work out the way you want, like "Little Dick" AKA
"troll zero"...remember, we're allegedly trying to "help" a confused
person here, but to do that, we have to "help" each other, right?

I'll correct that "error" now...

Maybe it's a mistake to NOT include it...I know this is hard,
but THINK...

Why not? Works for me...what's the disconnect?

OK, you're right, you don't have to THINK about anything at all
when programming...oh, that's right, you DO have to think when
programming, just not when posting to the Internet...
Is it the error you mentioned?

--- unquoted tool text ---
is *what* the error I mentioned? The error above occurs on
the line I indicated.
--- end tool text

He's asking you why your compiler reports an error, since his
may not under the same circumstances, you massive tool...
What does it warn about?

--- unquoted tool text ---
I have this trouble when people ask me to explain syntax errors.
To me (maybe I've been at this too long) they seem self explanatory
(maybe one day I'll say the same about a three page C++
template diagnostic (but not yet)).
--- end tool text

IBID (what a total tool this idiot is..)

--- unquoted tool text ---
Well it warns that the formal parameters does not
match the declaration. It even tells you which parameter (paramter 1).
Which
is nice of it but not very helpful as it only has one parameter.

The formal parameter appears in the definition
void my_library_function(int my_callback_function(const char*))

so the formal parameter is
int my_callback_function(const char*))

which is a function. This doesn't make much sense to me.
I'm surprised the compiler didn't get more upset.

The declaration is:
extern void my_library_function (int (*)(const char*));

so the parameter is
int (*)(const char*)

Formal is a ptr-to-function-taking-const-char*-and-returning-int

So what parameter is a function declaration and the other
is a function pointer. They don't match.
--- end tool text
Parameter is declared as a function, that's adjusted to
the pointer to a function. What exactly is wrong?

--- unquoted tool text ---
is it?
-- end tool text

Yes, you total tool, that's his conception about how function
pointers work, and basically mine...so here's my REALLY
compact version of the code THAT COMPILES COMPLETELY
CLEANLY FOR ME:

library_h.h

/* library_h.h */
/* library header file */

extern void my_library_function (int (*)(const char*));

library_c.c

/* library_c.c */
/* library "C" source */

#include "library_h.h"

void my_library_function(int my_callback_function(const char*)) {

}

I can compile library_c.c to library_c.obj without so much as
a warning, error, scolding, and then proceed likewise to build
library.lib...so in the interest of everybody learning something
today, other than you're a tool who doesn't know how to post
to Usenet, EXPLAIN THE DISCREPANCY..."spec lawyer" it,
tell us exactly what you did differently, whatever, just clear up
the confusion here...
 
Y

ymuntyan

is *what* the error I mentioned? The error above occurs on
the line I indicated.


I have this trouble when people ask me to explain syntax errors.

There isn't a syntax error (and your compiler agrees). If
you think a warning message is obviously "a syntax error",
then you're wrong.
To me (maybe I've been at this too long) they seem self explanatory
(maybe one day I'll say the same about a three page C++
template diagnostic (but not yet)).

Well it warns that the formal parameters does not
match the declaration. It even tells you which parameter (paramter 1).
Which
is nice of it but not very helpful as it only has one parameter.

The formal parameter appears in the definition
void my_library_function(int my_callback_function(const char*))

so the formal parameter is
int my_callback_function(const char*))

which is a function. This doesn't make much sense to me.
I'm surprised the compiler didn't get more upset.

It makes perfect sense, just like array parameters:
int a[] gets transformed ("adjusted" in standardese) to
int *a. See 6.7.5.3p8.

Does your compiler warn about this:

int func (int *a);
int func (int a[]);

Yevgen
 
Y

ymuntyan

Posting incorrect syntax won't help the OP. In fact, there is some
evidence that the OP knows the correct syntax for what they are doing
since the problem they report is a run time one. Only an example of
their actual code will help diagnose what they are doing wrong.

Perhaps you can tell what exactly was wrong? Richard Heathfield
refused to, Nick Keighley somehow made a syntax error of a
compiler warning, so maybe you can explain what this fuzz is
about? (Except Bill Reid being a troll, of course, which is
obvious and doesn't require any syntax errors or whatever
to be proved)

Yevgen
 
B

Ben Bacarisse

<snip lots>

Why do you have to be so angry? There is a technical matter here so I
will get stuck in, but I am wary of getting caught in the middle of a
flame war.
... that's his conception about how function
pointers work, and basically mine...so here's my REALLY
compact version of the code THAT COMPILES COMPLETELY
CLEANLY FOR ME:

library_h.h

extern void my_library_function (int (*)(const char*));

library_c.c

#include "library_h.h"

void my_library_function(int my_callback_function(const char*)) {
}

You must be aware that is this not the normal syntax. Usually, the
function definition is similar to the declaration, except the ';' is
replaced by the function body. Here, you have an odd-looking
parameter. Function pointer parameters usually look like this:

void my_library_function(int (*my_callback_function)(const char*)) {}

which is, of course, how you wrote it in the function's prototype.
This example *seems* to declare the parameter as a function, not a
pointer to one.
I can compile library_c.c to library_c.obj without so much as
a warning, error, scolding, and then proceed likewise to build
library.lib...so in the interest of everybody learning something
today, other than you're a tool who doesn't know how to post
to Usenet, EXPLAIN THE DISCREPANCY..."spec lawyer" it,
tell us exactly what you did differently, whatever, just clear up
the confusion here...

The answer is that there is a special dispensation:

A declaration of a parameter as ‘‘function returning type’’ shall be
adjusted to ‘‘pointer to function returning type’’

This is the same sort of special case that makes 'int x[]' be treated
as a pointer rather than an (un-passable) array. Your example is less
than clear for people learning the language or having trouble with
function pointers. I would not post it as an example to follow, but
it is correct.
 
J

John Bode

Hello

I am writing a library which will write data to a user defined callback
function. The function the user of my library will supply is:

int (*callbackfunction)(const char*);

In my libary do I create a function where user passes this callback
function? How would I define the function?

I tried this

callbackfunction clientfunction;

void SpecifyCallbackfunction(cbFunction cbFn)
{
clientfunction = cbFn;

}

Then called like this:
clientfunction(sz); // sz is a C-string.

But program crashes with access violation when attempt to call
clientfunction

What am I doing wrong?

Based on what you've written here, it sounds like you want to
"register" the callback so it can be called by other functions within
the library: is that correct? If so, here's one approach:

/* Library header file */
#ifndef LIB_H
#define LIB_H
/**
* Create a typedef for the function pointer type
*/
typedef int (*callback)(const char *);

/**
* Register the callback function
*/
void SpecifyCallbackfunction(callback f);

/**
* Other library functions that will use the callback
*/
void L1(const char *foo);
void L2(void);

#endif

/**
* Library implementation file
*/

/**
* File-scope global for callback
*/
static callback g_callback;

void SpecifyCallbackFunction(callback f)
{
g_callback = f;
}

void L1(const char *foo)
{
int bar = g_callback(foo);
...
}

void L2(void)
{
int bar = g_callback("DUMMY");
...
}

/**
* main
*/

#include "library.h"

int blah(const char *bletch)
{
int retVal;
retVal = /* result of doing something with bletch */
return retVal;
}

int main(void)
{
SpecifyCallbackFunction(blah);
L1("blurga");
L2();
...
return 0;
}

HTH.
 
Y

ymuntyan

(e-mail address removed) said:



You appear to have misunderstood.

The code posted by Bill Reid contained a bug.

Nick Keighley pointed out the bug.

No he didn't. He did talk about the warning produced
by his compiler, and called that warning "syntax error".
Now, there wasn't a syntax error. So, what's the bug?

Yevgen
 
B

Ben Bacarisse

Perhaps you can tell what exactly was wrong?

Nothing is wrong with the syntax (I posted further explanation else
elsethread). I did not look at the code properly. If I *had*
properly studied what Bill posted I might have phrased it like this:

| Posting obscure syntax won't help the OP. In fact, there is some
| evidence that the OP knows the correct syntax for what they are doing
| since the problem they report is a run time one. Only an example of
| their actual code will help diagnose what they are doing wrong.

with a note that the "adjusted" form of function parameter is not
common enough to be posted in a "you do it like usenet message".

My point was that the OP seemed not to be having trouble getting the
syntax since they were reporting a compile-time error. Posting an
alternative way to declare the parameter was not likely to clarify
anything for the OP. It certainly confused me, till checked the
standard.
 
B

Bill Reid

Ben Bacarisse said:
<snip lots>

Why do you have to be so angry?

I'm not really angry, but I am being trolled, as is anybody
who mistakenly wanders into this group thinking it is about
technical discussions related to the "C" programming
language. If I WAS a "bleeding-heart" about "newbies"
(think of the children!) like all of the hypocritical trolls
that infect the group, I WOULD be seething. It IS totally
reprehensible how the freaks here treat people who are
just trying to learn a programming language...and this
thread is a classic example...
There is a technical matter here so I
will get stuck in, but I am wary of getting caught in the middle of a
flame war.

Don't worry about that; remember that trolls like "Little Dick"
use a "hit-and-run" strategy of posting lies and then running
away to marvel at the chaos they've caused...but in the final
analysis, they're more pathetic than dangerous, EXCEPT
to the "newbies" (THINK OF THE CHILDREN!!!); they
can't really hurt an intelligent person, who should just ignore
them in the first place.
You must be aware that is this not the normal syntax.

Sure it is. I use it all the time, so it's normal to me.
Usually, the
function definition is similar to the declaration, except the ';' is
replaced by the function body.

Right. Let me clue you in on something about me: I try to
conserve keystrokes where they AREN'T needed, and use
them where they help me understand my own code.
Here, you have an odd-looking
parameter.

Sorry, but does your opinion of the color of a car's paint
affect how well it runs?
Function pointer parameters usually look like this:

void my_library_function(int (*my_callback_function)(const char*)) {}

Sure. But then I have to type "(*)" (three whole extra characters!)
where I don't need to type any more characters, because the two
ways of defining the parameters ARE TOTALLY FUNCTIONALLY
IDENTICAL.
which is, of course, how you wrote it in the function's prototype.

There, I'm forced to write it that way, unless I again want to
type unwanted characters...WHICH I DON'T.
This example *seems* to declare the parameter as a function, not a
pointer to one.

The key word, as you note, is "seems", since there is no
actual difference, despite how hard one of the "troll-ettes"
here has tried to convince innocent newbies otherwise.

This is why I feel pretty confident stating that most of the
posters here are technically incompetent (or they are just
shameless trolls, take your pick): they refer to "warnings"
as "errors" and "bugs", apparently not understanding the
meanings of those words in "C" programming, as well as
function names actually being, BY COMPLETE NECESSITY,
function pointers.

Nobody can make the mistakes that "troll zero" and
his "troll-ette" has made in this thread and not be justifiably
called technically incompetent (or again, just a troll, a
person who LIES to provoke newsgroup arguments; take
your pick).
The answer is that there is a special dispensation:

A declaration of a parameter as ''function returning type'' shall be
adjusted to ''pointer to function returning type''

Great, which of course completely conforms to the basic
idea above that a function name is actually a function pointer
by the simple necessity of computer science...I'm assuming
this is "standard" language, so despite you calling it a
"special dispensation" IT IS TOTALLY CONFORMING
"STANDARD" SYNTAX.
This is the same sort of special case that makes 'int x[]' be treated
as a pointer rather than an (un-passable) array. Your example is less
than clear for people learning the language or having trouble with
function pointers. I would not post it as an example to follow, but
it is correct.

Well, I'll give you this, you a) actually admitted it is "correct";
and b) gave an innocent "newbie" a fighting chance to be
able to write correct code despite all the misinformation and
sheer idiocy put out by "troll zero" and his "troll-ette"...of course,
since what I wrote was "correct" in the first place, it would
have been best had they just pointed out the "equivalency"
of function names and function pointers and showed the
simple "equivalent" function definition rather than all the juvenile
confusing trolling...

But I WARNED the "newbie" UP-FRONT that any "correct"
answer here would be trolled, so as usual, I'm "correct" about
EVERYTHING, but people even more so than programming...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top