473,772 Members | 2,292 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Passing static member function as callback to Windows DLL

Hi, all.

I have a Windows DLL that exports a number of functions. These functions
expect to receive a pointer to a callback function and an opaque void*
parameter. The callback functions are typedef'd to take void* parameters,
through which the DLL's function passes its void* parameter to the callback
function. This allows me to use class instances as callback handlers, as in
the example below.

//Executable and DLL know this:
typedef void (*callback)(voi d*);

//in DLL "Exporter.d ll":
void ExportedFn(call back cb, void *opaque) { cb(opaque); }

//in executable:
class CallbackHandler
{
public:
static void Thunk(void *fromDll)
{
CallbackHandler *handler = static_cast<Cal lbackHandler*>( fromDll);
...
}
};
....
HANDLE dllInst = ::LoadLibrary(" Exporter.dll");
typedef void (*DllExport)(ca llback, void*);
DllExport exportedFn = reinterpret_cas t<DllFn>(::GetP rocAddress(dllI nst,
"ExportedFn "));
CallbackHandler handlerInst;
exportedFn(Call backHandler::Th unk, &handlerInst ); /**/
....

What bothers me is that CallbackHandler ::Thunk() must have a void* parameter
to match the callback signature, even though it's part of the
CallbackHandler class and its fromDll parameter is and must be a
CallbackHandler *.

My question is, is there a 'best practices' way to let Thunk()s parameter be
a CallbackHandler * and yet have the line marked with /**/ compile? By 'best
practice', I mean less of a blunt instrument than reinterpret_cas t<or a
C-style cast.

-Evan
Aug 24 '07 #1
2 4127
Evan Burkitt wrote:
Hi, all.

I have a Windows DLL that exports a number of functions. These functions
expect to receive a pointer to a callback function and an opaque void*
parameter. The callback functions are typedef'd to take void* parameters,
through which the DLL's function passes its void* parameter to the callback
function. This allows me to use class instances as callback handlers, as in
the example below.

//Executable and DLL know this:
typedef void (*callback)(voi d*);

//in DLL "Exporter.d ll":
void ExportedFn(call back cb, void *opaque) { cb(opaque); }

//in executable:
class CallbackHandler
{
public:
static void Thunk(void *fromDll)
{
CallbackHandler *handler = static_cast<Cal lbackHandler*>( fromDll);
...
}
};
...
HANDLE dllInst = ::LoadLibrary(" Exporter.dll");
typedef void (*DllExport)(ca llback, void*);
DllExport exportedFn = reinterpret_cas t<DllFn>(::GetP rocAddress(dllI nst,
"ExportedFn "));
CallbackHandler handlerInst;
exportedFn(Call backHandler::Th unk, &handlerInst ); /**/
...

What bothers me is that CallbackHandler ::Thunk() must have a void* parameter
to match the callback signature, even though it's part of the
CallbackHandler class and its fromDll parameter is and must be a
CallbackHandler *.

My question is, is there a 'best practices' way to let Thunk()s parameter be
a CallbackHandler * and yet have the line marked with /**/ compile? By 'best
practice', I mean less of a blunt instrument than reinterpret_cas t<or a
C-style cast.
If you're stuck with having to call ::GetProcAddres s and pull names from
a DLL, so be it, however there are much more elegant ways of doing this.
One way of looking at this is that the DLL contains a number of
factories. Upon loading, the factories automagically register
themselves and you can avoid all of the casts. I use this technique
with DLL's and it's portable - no need to worry about mangled names.

Below is a suggestion - it uses templates to create yet another function
that calls the function you want. There are some limitations.

#include <iostream>

//Executable and DLL know this:
typedef void (*callback)(voi d*);

//in DLL "Exporter.d ll":
void ExportedFn(call back cb, void *opaque) { cb(opaque); }

template <typename T, void (*F)( T* )>
struct Thunker
{
static void Do( void * fromDll )
{
F( static_cast<T*> (fromDll) );
}
};

//in executable:
class CallbackHandler
{
public:
static void Thunk(CallbackH andler *handler)
{
std::cout << "callback handler called\n";
}
};

typedef void (*DllExport)(ca llback, void*);

template <typename T, void (*F)( T* )>
void CallDll( T * ptr, DllExport exfn )
{
exfn( & Thunker<T,F>::D o, static_cast<voi d *>( ptr ) );
}

//HANDLE dllInst = ::LoadLibrary(" Exporter.dll");
DllExport exportedFn = ExportedFn;

CallbackHandler handlerInst;

int main()
{
CallDll<Callbac kHandler,&Callb ackHandler::Thu nk>( & handlerInst,
exportedFn );
}
Aug 24 '07 #2

"Gianni Mariani" <gi*******@mari ani.wswrote in message
news:46******** *************** @per-qv1-newsreader-01.iinet.net.au ...
If you're stuck with having to call ::GetProcAddres s and pull names from a
DLL, so be it, however there are much more elegant ways of doing this. One
way of looking at this is that the DLL contains a number of factories.
Upon loading, the factories automagically register themselves and you can
avoid all of the casts. I use this technique with DLL's and it's
portable - no need to worry about mangled names.
Yes, this DLL exposes only a C interface, which will eventually be called by
non-C/C++ languages. I'm constrained to only use simple types for function
parameter lists and return types.
Below is a suggestion - it uses templates to create yet another function
that calls the function you want. There are some limitations.

#include <iostream>

//Executable and DLL know this:
typedef void (*callback)(voi d*);

//in DLL "Exporter.d ll":
void ExportedFn(call back cb, void *opaque) { cb(opaque); }

template <typename T, void (*F)( T* )>
struct Thunker
{
static void Do( void * fromDll )
{
F( static_cast<T*> (fromDll) );
}
};

//in executable:
class CallbackHandler
{
public:
static void Thunk(CallbackH andler *handler)
{
std::cout << "callback handler called\n";
}
};

typedef void (*DllExport)(ca llback, void*);

template <typename T, void (*F)( T* )>
void CallDll( T * ptr, DllExport exfn )
{
exfn( & Thunker<T,F>::D o, static_cast<voi d *>( ptr ) );
}

//HANDLE dllInst = ::LoadLibrary(" Exporter.dll");
DllExport exportedFn = ExportedFn;

CallbackHandler handlerInst;

int main()
{
CallDll<Callbac kHandler,&Callb ackHandler::Thu nk>( & handlerInst,
exportedFn );
}
In my case I can use your Thunker struct on the caller's side. Although for
completeness my example included a call to the callback as well, my
implementation only needs to supply a function pointer suitable (to the
compiler) for the signature of the callback. The actual call to it is made
from the DLL, which believes the parameter to be a void* anyway.

Using terminology from our examples, what I did boils down to:
ExportedFn(Thun ker<CallbackHan dler, &CallbackHandle r::Thunk>::Do,
&handlerInst );
This is still essentially a typecast, but wrapped up in such a way as to
cause compiler errors if the signature of CallbackHandler ::Thunk() changes,
which was my biggest objection to brute-force casting the function pointer
itself.

Working through this has forced me to learn a bit more about template usage.
I appreciate your help.

-Evan
Aug 24 '07 #3

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

Similar topics

7
2497
by: Steven T. Hatton | last post by:
I am trying to convert some basic OpenGL code to an OO form. This is the C version of the program: http://www.opengl.org/resources/code/basics/redbook/double.c You can see what my current effort at converting that code to an OO form looks like in the code listed below. The problem I'm running into is that the OpenGL functions that take the names of other functions as arguments don't like the way I'm passing the member functions of my...
6
8829
by: keepyourstupidspam | last post by:
Hi, I want to pass a function pointer that is a class member. This is the fn I want to pass the function pointer into: int Scheduler::Add(const unsigned long timeout, void* pFunction, void* pParam)
0
3290
by: Jeffrey B. Holtz | last post by:
Has anyone used the multimedia timere timeSetEvent in C#? I'm trying to use it to get a 1ms accurate timer. All the other implementations are far to inaccurate in their resolution. 1ms Timer = 0ms.....60ms. I'm already timing the callbacks using the Win32API QueryPerformanceCounter/Frequency. The code I have is actually performing the callback and it looks like it is close to 1ms but I now need to get my object passed to this static...
4
5144
by: H.B. | last post by:
Hi, I successfully implement a static callback function for my dll usign delegates. Now, I need to use member function instead of static function. How can I make that (in Managed C++). Hugo
12
11369
by: Haxan | last post by:
Hi, I have my main application class(unmanaged) that has a none static member function that I need to pass as a delegate to managed C# method. In one of the methods of this class(unmamanged), I am calling a managed C# method(I use gcnew to instantiate the managed class). One of the parameters of this C# method is a delegate. I need to pass the none static member function as a delegate(function pointer) as a parameter in the managed C#...
4
5903
by: Jimmy | last post by:
I need to use Asynchronous Socket functions in a server application and am learning from sources such as the MSDN2 (http://msdn2.microsoft.com/en-us/library/bbx2eya8.aspx). What I observed is that all callback handlers in examples are static functions. I did try non-static callback handlers; they certainly works, and they usually make my code simpler. For example, a typical tutorial will start an asynchronous connection with:
5
8908
by: Jon E. Scott | last post by:
I'm a little confused with "static" methods and how to access other unstatic methods. I'm a little new to C#. I'm testing a callback routine within a DLL and the callback function returns a string as one of the arguments. As shown below, I have no problems showing the string in the Report() method in a messagebox or console window, but how does one access a memo or label on a form from a static method? I want to throw the strings from...
6
7684
by: smmk25 | last post by:
Before I state the problem, I just want to let the readers know, I am knew to C++\CLI and interop so please forgive any newbie questions. I have a huge C library which I want to be able to use in a .NET application and thus am looking into writing a managed C++ wrapper for in vs2005. Furthermore, this library has many callback hooks which need to be implemented by the C++ wrapper. These callback functions are declared as "extern C...
8
1969
by: Neviton | last post by:
Is it possible ? There is any work around? Thanx
0
9621
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
10264
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10039
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
9914
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
8937
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6716
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
5355
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...
1
4009
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2851
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.