473,788 Members | 2,706 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

callbacks

Hi,

can anyone show me how to be able to pass the name of method to a dll
function which will call this method when something inside the dll calling
function happens.
Is this called a callback?

Are there any websites that show how to implement something like this
easily??
Nov 17 '05 #1
5 2582
Yes this is called a callback. You must just remember to "lock" your method
as "unsafe". If you do not so this the garbage collector might move your
methods' code around at some stage, and the DLL might call the "old" address
of your function ... which might not be the correct address ... causing some
problems, with difficult debugging!

"WAkthar" <wa*****@hotmai l.com> wrote in message
news:%2******** ********@TK2MSF TNGP14.phx.gbl. ..
Hi,

can anyone show me how to be able to pass the name of method to a dll
function which will call this method when something inside the dll calling
function happens.
Is this called a callback?

Are there any websites that show how to implement something like this
easily??

Nov 17 '05 #2

"Nico Gerber" <ng*****@telkom sa.net> wrote in message
news:O3******** ******@tk2msftn gp13.phx.gbl...
Yes this is called a callback. You must just remember to "lock" your
method as "unsafe". If you do not so this the garbage collector might move
your methods' code around at some stage, and the DLL might call the "old"
address of your function ... which might not be the correct address ...
causing some problems, with difficult debugging!


This is not true, code never moves, the GC only moves objects in the GC
heap, code is not store in the GC heap!

Willy.
Nov 17 '05 #3
Guys guys...
The guy is looking for code examples...

I hope this will clear some stuff:

On your Cpp side:

You need to define a function pointer such as:
typedef void (__stdcall *LPFN_MANAGED_C ALLBACK)(unsign ed int x,unsigned
int y);

** don't forget the __stdcall

and a method to receive the EventHandler from the Managed side such as:
void MyCppMethod(LPF N_MANAGED_CALLB ACK lpfnManagedCall back)
{
// To call the callback do:
lpfnManagedCall back(10 /*x value*/, 20 /*y value*/);
}
On the C# side:
1) you should define a delegate such as:
public delegate void PointEventHandl er(uint x, uint y);

2) a member to hold the PointEventHandl er so that it won't be
collected:
private PointEventHandl er m_pointCallback ;

3) a p/Invoke for the Cpp method:
[DllImport("CppD ll.dll", CallingConventi on=CallingConve ntion.StdCall)]
extern private static void CppMethod(Point EventHandler pointCB);

4) you need to create a method to handle the Cpp call:
private void CppCallbackHand ler(uint x, uint y)
{
Console.WriteLi ne("Received a call from Cpp with X={0} & y={1}", x,
y);
}

5) you need to create the callback:
m_pointCallback = new PointEventHandl er(CppCallbackH andler);

6) and now you can pass the callback to Cpp side:
CppMethod(m_poi ntCallback);

Cheers,
Eyal Safran

Nov 17 '05 #4
Thanks Eyal,

My scenario is a little different. There are two people involved in the
project.

I am writing the UI part and my collegue is writing a dll which will
communicate with teh serial port.

What we have is the ability for me to call functions that communicate with
the serial port. Now when certain events happen at the serial port, I need
to be notified.
To implement is I thought about using delegates as callbacks. The dll is
also written in C#.

When I create an object from the dll, I pass the function pointer (delegate)
to it. When an event happens on the serial port, this delegate is called and
I can update the UI.

Can you show how I can implement something like this please??

Thanks in advance!
"Eyal Safran" <ey**@mokedor.c om> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .
Guys guys...
The guy is looking for code examples...

I hope this will clear some stuff:

On your Cpp side:

You need to define a function pointer such as:
typedef void (__stdcall *LPFN_MANAGED_C ALLBACK)(unsign ed int x,unsigned
int y);

** don't forget the __stdcall

and a method to receive the EventHandler from the Managed side such as:
void MyCppMethod(LPF N_MANAGED_CALLB ACK lpfnManagedCall back)
{
// To call the callback do:
lpfnManagedCall back(10 /*x value*/, 20 /*y value*/);
}
On the C# side:
1) you should define a delegate such as:
public delegate void PointEventHandl er(uint x, uint y);

2) a member to hold the PointEventHandl er so that it won't be
collected:
private PointEventHandl er m_pointCallback ;

3) a p/Invoke for the Cpp method:
[DllImport("CppD ll.dll", CallingConventi on=CallingConve ntion.StdCall)]
extern private static void CppMethod(Point EventHandler pointCB);

4) you need to create a method to handle the Cpp call:
private void CppCallbackHand ler(uint x, uint y)
{
Console.WriteLi ne("Received a call from Cpp with X={0} & y={1}", x,
y);
}

5) you need to create the callback:
m_pointCallback = new PointEventHandl er(CppCallbackH andler);

6) and now you can pass the callback to Cpp side:
CppMethod(m_poi ntCallback);

Cheers,
Eyal Safran

Nov 17 '05 #5
Hi,
When I create an object from the dll, I pass the function pointer (delegate)
to it. When an event happens on the serial port, this delegate is called and
I can update the UI.

Can you show how I can implement something like this please??

Thanks in advance!


well it's you lucky day, (I hope thats what you ment).
I already wrapped unmanaged code to interact with the serial port:

[Flags]
public enum CommEvents
{
/// <summary>
/// No events
/// </summary>
EV_NONE = 0x0000,
/// <summary>
/// Any Character received
/// </summary>
EV_RXCHAR = 0x0001,
/// <summary>
/// Received certain character
/// </summary>
EV_RXFLAG = 0x0002,
/// <summary>
/// Transmit Queue Empty
/// </summary>
EV_TXEMPTY = 0x0004,
/// <summary>
/// CTS changed state
/// </summary>
EV_CTS = 0x0008,
/// <summary>
/// DSR changed state
/// </summary>
EV_DSR = 0x0010,
/// <summary>
/// RLSD changed state
/// </summary>
EV_RLSD = 0x0020,
/// <summary>
/// BREAK received
/// </summary>
EV_BREAK = 0x0040,
/// <summary>
/// Line status error occurred
/// </summary>
EV_ERR = 0x0080,
/// <summary>
/// Ring signal detected
/// </summary>
EV_RING = 0x0100,
/// <summary>
/// Printer error occurred
/// </summary>
EV_PERR = 0x0200,
/// <summary>
/// Receive buffer is 80 percent full
/// </summary>
EV_RX80FULL = 0x0400,
/// <summary>
/// Provider specific event 1
/// </summary>
EV_EVENT1 = 0x0800,
/// <summary>
/// Provider specific event 2
/// </summary>
EV_EVENT2 = 0x1000
}

protected CommEvents commEvents = CommEvents.EV_N ONE;
private EventHandlerLis t events;

protected EventHandlerLis t Events
{
get
{
if (events == null)
{
lock(this)
{
if (events == null)
{
events = new EventHandlerLis t();
}
}
}
return events;
}
}

// Event objects
private static readonly object EventCharacterR eceived;
private static readonly object EventCertainCha racterReceived;
private static readonly object EventTransmitQu eueEmpty;
private static readonly object EventCTSStateCh anged;
private static readonly object EventDSRStateCh anged;
private static readonly object EventRLSDStateC hanged;
private static readonly object EventBreakRecei ved;
private static readonly object EventLineStatus ErrorOccurred;
private static readonly object EventRingSignal Detected;
private static readonly object EventPrintError Occurred;
private static readonly object EventReceiveBuf ferIs80PercentF ull;
private static readonly object EventProviderSp ecificEvent1;
private static readonly object EventProviderSp ecificEvent2;

static Port() // static constructor
{
EventCharacterR eceived = new object();
EventCertainCha racterReceived = new object();
EventTransmitQu eueEmpty = new object();
EventCTSStateCh anged = new object();
EventDSRStateCh anged = new object();
EventRLSDStateC hanged = new object();
EventBreakRecei ved = new object();
EventLineStatus ErrorOccurred = new object();
EventRingSignal Detected = new object();
EventPrintError Occurred = new object();
EventReceiveBuf ferIs80PercentF ull = new object();
EventProviderSp ecificEvent1 = new object();
EventProviderSp ecificEvent2 = new object();
}

// example to an event "Character Received" you register on:
public event EventHandler CharacterReceiv ed // Any Character received
{
add
{
if (Events[EventCharacterR eceived] == null)
{
commEvents |= CommEvents.EV_R XCHAR;
SetEvents();
}
Events.AddHandl er(EventCharact erReceived, value);
}
remove
{
Events.RemoveHa ndler(EventChar acterReceived, value);
if (Events[EventCharacterR eceived] == null)
{
commEvents &= ~CommEvents.EV_ RXCHAR;
SetEvents();
}
}
}

protected void SetEvents()
{
if (commEvents == CommEvents.EV_N ONE)
{
return;
}
if (Trace.debug())
{
Trace.debug("Se tting {0} communication port events:\n{1}", PortName,
commEvents);
}
bool result = _SetCommMask(hP ort, (int)commEvents );
if (result == false)
{
throw new CommunicationEx ception("Failed to SetCommMask (set the
events)");
}
}

[DllImport("kern el32.dll", EntryPoint="Set CommMask",
SetLastError=tr ue,
CharSet=CharSet .Unicode, ExactSpelling=t rue,
CallingConventi on=CallingConve ntion.StdCall)]
protected static extern bool _SetCommMask(
Int32 hFile,
int lpEvtMask);

[DllImport("kern el32.dll", EntryPoint="Wai tCommEvent",
SetLastError=tr ue,
CharSet=CharSet .Unicode, ExactSpelling=t rue,
CallingConventi on=CallingConve ntion.StdCall)]
protected static extern bool _WaitCommEvent(
Int32 hFile,
ref CommEvents Mask,
IntPtr lpOverlap);

public void WaitForEvents()
{
if (commEvents == CommEvents.EV_N ONE)
{
throw new CommunicationEx ception("No events have been registered.");
}
CommEvents eventsReceived = CommEvents.EV_N ONE;
bool result = _WaitCommEvent( hPort, ref eventsReceived, IntPtr.Zero);
if (result == false)
{
throw new CommunicationEx ception("Failed Waiting for comm events.");
}
// CharacterReceiv ed
object[] args = new object[]{this, EventArgs.Empty };
EventHandler invoker = null;
if ((eventsReceive d & CommEvents.EV_R XCHAR) == CommEvents.EV_R XCHAR)
{
invoker = (EventHandler)E vents[Port.EventChara cterReceived];
if ( invoker != null)
{
invoker.Dynamic Invoke(args);
}
}
}
Remark:
In this code, the user registers on the events, the first registration
on each event adds a flag to the member: "commEvents ".
After all the clients unregistered from an the event, the flag is
removed from: "commEvents ".

The collection of events is sent to the RS-232 port.

when the WaitForEvents is called, the thread is waiting for any of the
registered events to occur.
When they do, the C# event of the corresponding RS-232 event is
triggered.

Eyal.

Nov 17 '05 #6

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

Similar topics

1
2297
by: Melissa Wallis | last post by:
I have a class with 5 callbacks. Two of the callbacks work fine but the others don't. The main difference is that the callbacks that don't work are composed of a sequence of structs. I noticed a comment about this same problem on the web but no solution was noted. What makes the callbacks with the sequences so different? It seems that when one of the callbacks with a sequence is called it just hangs. I am talking to a TAO orb from...
2
2085
by: Mike C. Fletcher | last post by:
I'm looking at rewriting parts of Twisted and TwistedSNMP to eliminate __del__ methods (and the memory leaks they create). Looking at the docs for 2.3's weakref.ref, there's no mention of whether the callbacks are held with a strong reference. My experiments suggest they are not... i.e. I'm trying to use this pattern: class Closer( object ): """Close the OIDStore (without a __del__)""" def __init__( self, btree ): """Initialise the...
1
1918
by: vijaya | last post by:
I've to invoke a unmanaged dll fucntion in C# which uses a callback fucntion.The unmanaged dll fucntion returns a pointer to a structure to its callback fucntion.The user should collect those structure fields in a buffer. In my managed code(i.e. in C# program), I've used a delegate for invoking callback function and I've declared the structure too. The dll fucntion is executing finely without any errors but I'm not getting any values...
0
2736
by: ck388 | last post by:
For some reason when I enable the callback feature of the gridview I still get a page refresh, that is it seems like there is a postback that occurs, not a callback which is just supposed to update not the whole page, but a portion of the page. Strangely enough the URL below http://beta.asp.net/QUICKSTARTV20/aspnet/doc/ctrlref/data/gridview.aspx (VB GridView Paging and Sorting Callbacks example)
2
1662
by: johny smith | last post by:
I cannot seem to figure out how to do instance based callbacks for some reason. I found one site on functors but I did not find it that helpful actually I just don't understand it. I have no problem doing non-instance based callbacks. I want to be able to pass a function into a constructor and from inside the class make a call make a call to the instance based function of another class. Do i have to use templates?
5
3247
by: Christopher Jastram | last post by:
I'm a self-taught programmer, so this might be a pretty dumb question. If it is, please point me in the right direction and I shall apologize profusely. I have a question regarding C++ and object members. Can anyone help? I'm writing a C++ wrapper for a fairly old programming interface to a document editing program that has no OOP whatsoever; only tons of structs. This program has different callbacks I'm supposed to implement for...
4
3375
by: womanontheinside | last post by:
I have a library which was written in C, you call a function, it provides the result by a callback to specific function names. I am trying to wrap the calls to this inside a class, but this causes a problem with the callbacks, for example: class X { public: add(); };
0
1147
by: anilkoli | last post by:
I want clear cut idea about callbacks and also of delegates I have doughts about callbacks, I feel callbacks are used for 1. recursion 2. dynamically calling a perticular method out of many methods, deciding at runtime. 3. Notification
9
3345
by: zholthran | last post by:
Hi folks, after reading several threads on this issue (-> subject) I fear that I got a problem that cannot easily be solved by the offered workarounds in an acceptable way, at least not with my limited c & c++ experience. Maybe some of you can help. the problem: I need several instances of a class whose (non-static!) methods should serve as callbacks for a dll (which can' be manipulated/adapted in any
13
3054
by: noone | last post by:
consider the following problem: You have a C style library and API that uses callbacks to implement functionality. Examples of this are X11 API, OpenGL/GLUT...The List goes on. The power of virtuals in C++ leads us to want to implement a framework where those callbacks are simply overriden virtual methods in a derived class. So...
0
9656
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
10370
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
10113
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
9969
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...
1
7519
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5402
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...
0
5538
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3677
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2896
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.