vendredi 27 février 2015

Access to C struct function pointer by C++ class


I want to write an event handler that runs a callback function when a bzip2 (v1.0.6) block is closed.


Starting with the bz_stream struct in bzlib.h, I add a function pointer to it as a member:



typedef struct {
/* all the usual bz_stream member variables... */
void (*block_close_callback)();
} bz_stream;


In my C++ header (foo.h), I declare a callback method signature for my_callback, and attempt to set block_close_callback to this method when initializing a bz_stream * instance in the constructor:



#ifndef FOO_H
#define FOO_H

#include <cstdio>
#include <cstdlib>
#include "bzlib.h"

namespace foo {
class Foo {
private:
bz_stream* _bz_stream_ptr;
public:
Foo();
~Foo();
bz_stream* get_bz_stream_ptr(void);
void set_bz_stream_ptr(bz_stream** ptr);
void free_bz_stream_ptr(void);
static void my_callback(void);
};
bz_stream* Foo::get_bz_stream_ptr(void) { return _bz_stream_ptr; }
void Foo::set_bz_stream_ptr(bz_stream** ptr) { _bz_stream_ptr = *ptr; }
void Foo::free_bz_stream_ptr(void) { free(_bz_stream_ptr); _bz_stream_ptr = NULL; }

Foo::Foo() {
bz_stream* bz_stream_ptr = NULL;
bz_stream_ptr = static_cast<bz_stream *>( malloc(sizeof(bz_stream)) );
if (!bz_stream_ptr) {
fprintf(stderr, "Error: Could not allocate space for bz stream\n");
exit(ENOMEM);
}
bz_stream_ptr->block_close_callback = my_callback;
set_bz_stream_ptr(&bz_stream_ptr);
}

Foo::~Foo() {
if (get_bz_stream_ptr()) {
free_bz_stream_ptr();
}
}
}

#endif


In the definition (foo.cpp), I define the callback function void foo::Foo::my_callback(void):



#include "foo.h"

int main(int argc, char** argv) {
return EXIT_SUCCESS;
}

void foo::Foo::my_callback(void) {
fprintf(stderr, "Callback called\n");
}


When I try to compile the C++ class, I get the following error:



error: no member named 'block_close_callback' in 'bz_stream'


What am I doing wrong in my modification to bzlib.h, such that the C++ class is unable to access this struct member?




Aucun commentaire:

Enregistrer un commentaire