Re: Passing C++ template functions (static members) as C callbacks
On Jun 5, 5:51 pm, Ema <oriani.blue_re...@bancaimi.it> wrote:
I'm trying to interface a C library built with compiler A (in this
case Sun CC) with a template class compiled with compiler B (in this
case GNU/g++).
Mathias Gaunard <loufoque@gmail.com> wrote:
How the hell can a template function follow the C ABI?
A template generates functions with the parameters you provide,
meaning each generated function will be given some name.
With the C ABI, you need one unique name.
If the function is used as a callback, its name doesn't matter.
And nobody said that the template parameters have to be used as
function parameters. For example:
extern "C" {
typedef unsigned int pthread_key_t;
int pthread_key_create(pthread_key_t*, void(*)(void*));
int pthread_key_delete(pthread_key_t);
int pthread_setspecific(pthread_key_t, const void*);
void* pthread_getspecific(pthread_key_t);
}
template<class T>
class thread_specific_ptr
{
public:
thread_specific_ptr()
{ pthread_key_create(&key_, &destroy_); }
~thread_specific_ptr()
{ pthread_key_delete(key_); }
T& operator*()
{
T* p = static_cast<T*>(pthread_getspecific(key_));
if (p == 0)
{
p = new T;
pthread_setspecific(key_, p);
}
return *p;
}
// ...
private:
/*extern "C"*/ static void destroy_(void* p)
{ delete static_cast<T*>(p); }
pthread_key_t key_;
// ...
};
Note that thread_specific_ptr::destroy_() has the same signature but
a different implementation for each template instantiation. But the
call to pthread_key_create() passes a pointer to a C++ function where
a pointer to a C function is expected.
The commented out <<extern "C">> is not valid, but it would be nice
if it were (or some other syntax that gave the same result).
--
Matt Messina
messina@yahoo.com
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]