Adapting a C-style callback mechanism to C++

  • Permalink
  • submit to reddit
  • Email
  • Follow


I'm using a C API (it's actually Spidermonkey's jsapi) with which I
can register callback functions:

void registerCallback(const char * name, CStyleFunctionPtr callback);

I'm trying to wrap and abstract away this API from my users by
offering a pure C++ interface, in which users could implement callback
via functions objects, or something similar. e.g.:

struct FooCallback : public CallbackFunction
{
	virtual void run() { /* ... /* }
}

void registerCppCallback(CallbackFunction * pCB);

You get the point. This way my callbacks have state, I don't need to
mess around with function pointers, my users don't have to even
#include the C-API's headers and I can translate their arguments from
the underlying API's C types to their equivalent STL classes.

My plan was to implement this by creating one "master" callback the C-
way and have it act as a dispatcher to the actual callback
implementations in C++.

The problem is that, with the C API I'm working, the callback
function's signature doesn't specify which function is being called.
So if I register more than one callback with the same master callback
function I have no way of knowing how to dispatch the call. So I'm
stuck basically.

The above code is a simplified version of the actual C interface I'm
working with. If you're interested, the actual API is jsapi (Mozilla's
implementation of Javascript) and what I'm trying to do is use the
JS_DefineFunction call to bridge between Javascript and C++ by
allowing Javascript code to call C++ functions/functors.


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply assaflavie (8) 7/18/2007 7:00:55 AM

See related articles to this posting


assaf <assaflavie@gmail.com> wrote in news:1184758436.991084.129780
@z24g2000prh.googlegroups.com:

> I'm using a C API (it's actually Spidermonkey's jsapi) with which I
> can register callback functions:
> 
> void registerCallback(const char * name, CStyleFunctionPtr callback);
> 
> I'm trying to wrap and abstract away this API from my users by
> offering a pure C++ interface, in which users could implement callback
> via functions objects, or something similar. e.g.:
> 
> struct FooCallback : public CallbackFunction
> {
>      virtual void run() { /* ... /* }
> }
> 
> void registerCppCallback(CallbackFunction * pCB);
> 
> You get the point. This way my callbacks have state, I don't need to
> mess around with function pointers, my users don't have to even
> #include the C-API's headers and I can translate their arguments from
> the underlying API's C types to their equivalent STL classes.
> 
> My plan was to implement this by creating one "master" callback the C-
> way and have it act as a dispatcher to the actual callback
> implementations in C++.
> 
> The problem is that, with the C API I'm working, the callback
> function's signature doesn't specify which function is being called.
> So if I register more than one callback with the same master callback
> function I have no way of knowing how to dispatch the call. So I'm
> stuck basically.

I'm a little unclear what you mean here.  Wouldn't you be registering
by name?

> The above code is a simplified version of the actual C interface I'm
> working with. If you're interested, the actual API is jsapi (Mozilla's
> implementation of Javascript) and what I'm trying to do is use the
> JS_DefineFunction call to bridge between Javascript and C++ by
> allowing Javascript code to call C++ functions/functors.
> 
> 

Have a look at Boost/TR1 function:
http://www.boost.org/doc/html/function/tutorial.html#id1186501
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2002/n1402.html

Your storage could be something like std::map<std::string,
boost::function<...> > if your functions have the same signature.  The
function objects are typesafe and can store all sorts of functions,
including function pointers, functors, and binders.

The JSNative function pointer type was not immediately availabe in a
search, so you'll have to match that.

You could have something like this:
class CallbackMgr
{
    typedef CallbackT boost::function<int(int)>; //whatever JSNative is
    typedef ContainerT std::map<
        std::string,
        CallbackT>;
    ContainerT container;
public:
    // returns true if replacing old value
    bool register(const char * name, CallbackT callback)
    {
        return container.insert(std::make_pair(
            std::string(name),
            callback)).second;
    }
    int execute(const char * name, int arg)
    {
        ContainerT::const_iterator i = container.find(std::string(name));
        if (i != container.end) return i->second(arg);
        // do not-found error processing here...
    }
};

There's a minor drawback: std::string is kind of heavy as a key, so
you might want to look at yasli or Alexandrescu's article on maps with
expensive keys.  I doubt you really care.

You'll probably want to wrap all the various types for your own
sanity...

Generally if you have separable or fine-grained callback needs, then
Boost/TR1 function is the way to go.  If you have callbacks grouped
together logically and they all should be implemented, then it's
better to group them in a class having virtual functions:

// user must inherit and implement, see Non-Virtual Interface
class CallbackGroup
{
public:
    void f1() { f1Imp(); }
.....
    void fn() { fnImp(); }
    virtual ~CallbackGroup() = 0 { }
private:
    virtual void f1Imp() = 0;
.....
    virtual void fnImp() = 0;
};

-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply W 7/18/2007 3:28:38 PM

assaf wrote:
> I'm using a C API (it's actually Spidermonkey's jsapi) with which I
> can register callback functions:
> 
> void registerCallback(const char * name, CStyleFunctionPtr callback);

Two questions here:
1. How does 'CStyleFunctionPtr' look like?
2. What is 'name' used for?

> I'm trying to wrap and abstract away this API from my users by
> offering a pure C++ interface, in which users could implement callback
> via functions objects, or something similar. e.g.:
> 
> struct FooCallback : public CallbackFunction
> {
> virtual void run() { /* ... /* }
> }
> 
> void registerCppCallback(CallbackFunction * pCB);
> 
> You get the point.

Ahem, not really: my first question would be who owns 'pCB' afterwards.

> This way my callbacks have state, I don't need to 
> mess around with function pointers,

...instead you mess around with object pointers with unclear ownership?
Seriously, consider either using references or use auto_ptr to make
ownership clear.

> my users don't have to even 
> #include the C-API's headers and I can translate their arguments from
> the underlying API's C types to their equivalent STL classes.
> 
> My plan was to implement this by creating one "master" callback the C-
> way and have it act as a dispatcher to the actual callback
> implementations in C++.
> 
> The problem is that, with the C API I'm working, the callback
> function's signature doesn't specify which function is being called.
> So if I register more than one callback with the same master callback
> function I have no way of knowing how to dispatch the call. So I'm
> stuck basically.

Okay. Typically, a C-style callback interface takes a function pointer and a
void pointers that holds some user-defined context. In you case, it could
only be the 'name', therefore also my initial two questions. If no such
thing is provided, there is nothing you can do. Otherwise, you could either
use the context to map to the object making the request or make the context
a pointer to the object itself.

Uli


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply Ulrich 7/19/2007 8:55:15 AM
comp.lang.c++.moderated 10662 articles. 10 followers. Post

2 Replies
301 Views

Similar Articles

[PageSpeed] 29


  • Permalink
  • submit to reddit
  • Email
  • Follow


Reply:

Similar Artilces:

Better C/C++ Than C/C++?
I am looking for a good systems programming language that can be used instead of C/C++. My qualifications for the language are: * mature compiler(s) that produce native-code binaries (for Windows) * open source - preferable, but not 100% necessary Thanks, Kevin "Kevin Albrecht" <kevin@albrecht.net> writes: > I am looking for a good systems programming language > that can be used instead of C/C++. My qualifications > for the language are: > > * mature compiler(s) that produce native-code > binaries (for Windows) Ocaml, D, cyclone, Eiffel, Beta >...

jython and C-c C-c
How do I get C-c C-c to work with jython? I have the jpython command set to jython, and I can start the interpreter with C-C ! and then use C-c C-c, but this is rather frustrating. If I try to use C-c C-c without first starting the interpreter in another window I get wrong type argument: sequencep, jpython Thanks, Dave Cook ...

C++ code with C-style interface for a library to be used in C++ and C?
Hi! I have a question about building and then using libraries containing C++ code. Let's say I have some C++ code and a .cpp file with 1 function that uses some other C++ code / classes etc... Also, any possible exception is handled within the function itself. In code: MyModule.h ---------- #ifndef MYMODULE_H #define MYMODULE_H extern int Test(float inParam1,float inParam2,float* outResult); #endif // #ifndef MYMODULE_H MyModule.cpp ------------ #include "MyModule.h" #include "MyClasses.h" // contains MyClassA and MyClassB int Test(float inParam1,float inParam2,...

Callback into C++ from C
I have legacy C code that performs some required functionality. I want to notify my C++ classes after work has been completed in the C code. In otherwords, I need to call a C++ method from C. Some PSEUDO code may help: /* C++ code */ class MyFooClass { public: NotifyHandler(); }; /* C code */ #ifdef __cplusplus extern "C" { #endif void foo() { /* Do some work */ /* finish work */ /* Notify C++ class via callback here */ } #ifdef __cplusplus }; #endif Anonymous wrote: > I have legacy C code that performs some required functionality. I want > to notify...

c------->c++ and c++------>c
We can write c program in turbo c++ editor.But reverse is not true why? i.e The program will not compile if u write c++ program in turbo c editor vim wrote: > We can write c program in turbo c++ editor.But reverse is not true why? > i.e The program will not compile if u write c++ program in turbo c > editor This isn't about C; this is about some editor. Why the fircone should /we/ know? Ask in a relevant group. [And /why/, in an editor specialised to some specific programming languages, would you expect it to compile a /different/ one? Would you expect turbo perl to compi...

C/C++ in matlab and matlab in C/C++ ?
Is it possible to read C/C++ code in matlab and the other way around too? Hi, as long as C or C++ are written in text files you can edit them in the matlab editor. To see the special character of C or C++ coding language, in the editor go to menus: file>preferences>Edito/Debugger>language and on popup "Language" select "C/C++". This does not allow you to run the C/C++ code, just to view it i nicer way... regards, chris saneman <asdfsdf@asd.com> wrote in message <frl846 $f8i$2@news.net.uni-c.dk>... > Is it possible to read C/C...

C as a Subset of C++ (or C++ as a superset of C)
Isn't it a lame use of human time and effort to maintain completely separate C and C++ standards? As in the words of Betty White about Facebook: "It seems like an incredible waste of time". Why don't the two standards groups get together and agree on a common specification for the ground which both standards cover? There would still be two separate standards, but they'd both be exactly the same for the common ground. The common ground document could be referred to by both standards instead of being maintained by both groups in individual efforts resulting in...

C/C++ in MATALB or MATLAB in C/C++?
Hi I've been asking on the net how to use MEX properly so that I can use C/C++ in MATLAB, but information is not forthcoming. There seems to be a lot on using MATLAB in C/C++ but not the other way around. I understand Mathworks is trying very hard to sell the Matlab Compiler, but even so, why is it SO hard to get information about MEX? Or is it that I've missed something very fundamental, meaning that I'm struggling over something that is actually quite easy? Any thoughts and info would be great. Thanks BullDog BullDog wrote: > Hi > > I've been asking on the net ...

C, C++ and C# Forums
Throne Software has opened up C, C++ and C# Forums at: http://www.thronesoftware.com/forum/ Join us! In article <1120963701.862698.160260@g14g2000cwa.googlegroups.com>, Throne Software <mail@thronesoftware.com> writes >Throne Software has opened up C, C++ and C# Forums at: > >http://www.thronesoftware.com/forum/ > >Join us! Why? The beauty of news groups is that they come to me I don't have to go to them. Also all the people who have been around a while know what they are doing and are here. I noticed that there are some C and C++ Forums on another system...

C, C++ and C# Forums
Throne Software has opened up C, C++ and C# Forums at: http://www.thronesoftware.com/forum/ Join us! Throne Software wrote: > Throne Software has opened up C, C++ and C# Forums at: > > http://www.thronesoftware.com/forum/ For all of your forums newsgroups already exist. > Join us! Why? Don't see any reason to support your marketing. ...

c,c++,obj-c
Of the 3 languages titled in this post is c++ older than obj-c ? Would someone experienced in C be able to dive right into C++ rather than obj-c ? Java is out for me now except applet programming I think I'm going to go with just C and C++. Bill Bill Cunningham wrote: > Of the 3 languages titled in this post is c++ older than obj-c ? Why does that matter? Do you want to use an old language? Try Fortran or LISP. > Would > someone experienced in C be able to dive right into C++ rather than > obj-c ? Not quite dive in, at least not into the OO parts of C++. ...

C,, C++, Java, C#
I come from C,C++,Java and C#. What can SmallTalk do for me and for what cost? Regarding the Squeak thing, it's interesting though confusing. Is it an IDE? Why are the menus so wacky? "DM McGowan II" <nospam@nospam.net> wrote in message news:PLednX2vnLd11IncRVn-rA@comcast.com... > I come from C,C++,Java and C#. What can SmallTalk do for me ...? Ask not what Smalltalk can do for, but what can you do with Smalltalk. :-) In very few words, it significantly reduces time to market, while enhancig the development experience. This is because: 1. It...

C, C++ and C# Forums
Throne Software has opened up C, C++ and C# Forums at: http://www.thronesoftware.com/forum/ Join us! ...

C++ or C?
I am new to MPI and have a basic understanding of C and C++. So I was wondering if any of you guys with experience in using MPI had any pointers with regards choosing either C or C++. I intend to use MPI in parallelizing code I have that was written in Java. So obviously the Java code it is heavly object orientated. With regards parallelizing it; right now I think it will mainly be a Master-Slave style of design with no inter-process communication needed once the master has sent the work to the slave. Most, if not all, of my communications will involve simply sending a large object from the ...

c++/c
hi i have been recently told that there is no exception handling ic c+ +.?? as far as i remember i have read, it has. also java has exception handling for sure but there we can use finally also which we cant use in c ++. what other differences do we have in the two languages c++ and java in exception handling. and which one is better? rupika wrote: > > i have been recently told that there is no exception handling ic > c++.?? You should ask about C in comp.lang.c, about C++ in comp.lang.c++. -- [mail]: Chuck F (cbfalconer at maineline dot net) [page]: <http://cbfalconer.home...

C++ to C
Are there any open source C++ compilers that will produce C code? I understand the first C++ compilers operated this way. On Mon, 27 Oct 2003 23:07:19 GMT, "Bootstrap Bill" <wrcousert@yahoo.com> wrote in comp.lang.c: > Are there any open source C++ compilers that will produce C code? I > understand the first C++ compilers operated this way. C++ compilers are off-topic in comp.lang.c. -- Jack Klein Home: http://JK-Technology.Com FAQs for comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html comp.lang.c++ http://www.parashift.com/c++-faq-lite/ alt.comp.lang.learn.c-...

C and C++
Hello, I have been having trouble getting used to C. A very simple language. Could this be because I was very familiar with C++ before trying to learn C? The fstream header is so simple. using fopen, fread and fwrite for example seems complicated. Bill "Bill Cunningham" <nospam@nspam.com> writes: > I have been having trouble getting used to C. A very simple > language. Could this be because I was very familiar with C++ before trying > to learn C? The fstream header is so simple. using fopen, fread and fwrite > for example seems compli...

C and C
Please Who wants to post Command and Conquer Red Alert 3. I'm looking for the whole version. If you do so Thank you. --------------= Posted using GrabIt =---------------- ------= Binary Usenet downloading made easy =--------- -= Get GrabIt for free from http://www.shemes.com/ =- Shaniel's Usenet wrote: > Please > Who wants to post Command and Conquer Red Alert 3. > I'm looking for the whole version. > If you do so Thank you. > > > --------------= Posted using GrabIt =---------------- > ------= Binary Usenet downloading made easy =--------- &g...

What After C and C++?
First it was C, then C++, what comes next? "Penna Elabi" <terebinthus@go.com> wrote in message news:77081966.0311290846.3d5a7064@posting.google.com... > First it was A whole bunch of computer languages, then >C, then a whole bunch more computer languages, then >C++, what comes next? A whole bunch more. So what? Did you have a question about C++ (which is the *only* topic here) ? -Mike "Penna Elabi" <terebinthus@go.com> wrote... > First it was C, then C++, what comes next? Who cares? This newsgroup is concerned with C++, not with what c...

C or C++?
Hi, I am a newbie to programming, and sorry again that I have to ask the C or C++ questions. Is C required before learning C++? And become better in C does it also make you a better C++ programmer? Or that to be a C+ + programmer, it's better not to have any knowledge of C and start a new in the C++ way as some books suggest? weidongtom@gmail.com wrote: > Hi, > > I am a newbie to programming, and sorry again that I have to ask the C > or C++ questions. Is C required before learning C++? No. And become better > in C does it also make you a better C++ programmer? Not n...

C++ to C
Hi all, does anyone out there have an awk/sed/perl script to assist me with manual rewriting from C++ to C? (Class --> struct, method --> function, << >> to printf, etc...) I have to rewrite a lot of legacy C++ code into a C-dialect of Plan 9 OS [sweetest Os around ;-) ] http://plan9.bell-labs.com/plan9/ Thanks, regards, ++pac. tyapca7@gmail.com wrote: > does anyone out there have an awk/sed/perl script to assist me with > manual rewriting from C++ to C? I'd ask a C language group... Yours, Laurenz Albe This is a MIME GnuPG-signed message. If you see this t...

c and c++
what do i do to learn c and c++,i hope to become a programmer in future.what are the materials needed for a beginner like me mama wrote: > what do i do to learn c and c++,i hope to become a programmer in > future.what are the materials needed for a beginner like me For a start... patience. Ben Pope -- I'm not just a number. To many, I'm known as a string... "mama" <tawwa2003@yahoo.com> wrote in message news:1133869392.103644.215390@g49g2000cwa.googlegroups.com... > what do i do to learn c and c++,i hope to become a programmer in > future.what are the...

C or C++
i would like someone with experience to answer my question ! C or C++ and why? Which one is stronger ? The criteria are yours! Thanks in advance guys. -- --------------------------------- --- -- - Posted with NewsLeecher v3.7 Final Web @ http://www.newsleecher.com/?usenet ------------------- ----- ---- -- - vadam17@hotmail.com ha scritto: > i would like someone with experience to answer my question ! C or > C++ and why? Which one is stronger ? The criteria are yours! > Thanks in advance guys. why cat or dog ? they are 2 different animals .... it is the same ... in my opinion...

C C++
While reading some source code, I saw a variable called "end" of type "time". So I investigated what the type "time" meant and saw that time was a typedef for "Real". So what does "Real" mean? "Real" is a typedef for QL_REAL. So what does "QL_REAL" mean? QL_REAL is type double via the line of code #define QL_REAL double.... "Mallik * G" <gadde.mallik@gmail.com> wrote in message news:7e4a882c-6f46-46eb-aa54-903842fa1b4d@p39g2000prm.googlegroups.com... > While reading some source code, I saw a variable cal...