passing a delegate to a C function.

J

James

I have a dll written in C. I call this C function from my C# code.
Within the C function(in dll) it should be able to call a function in
C#(Callback function). So when I call the C function I need to pass a
pointer to the C# function. I use delegates within my C# code for
other reasons, but could I use this method. Can anybody help. Thanks
in advance.
 
N

Nick Harris

Try using an unsafe block of code, wherein you can createa ptr handle to
your function, and pass that address in to your C dll for the call back.

Nick Harris, MCSD
 
R

Richard Grimes [MVP]

James said:
I have a dll written in C. I call this C function from my C# code.
Within the C function(in dll) it should be able to call a function in
C#(Callback function). So when I call the C function I need to pass a
pointer to the C# function. I use delegates within my C# code for
other reasons, but could I use this method. Can anybody help. Thanks
in advance.

What is the error? It would help if you showed some code. Delegates should
work fine because they will automatically add thunking for you. However, you
do have to take GC references into account, you have to make sure that data
being accessed does not move in the GC heap while the thread is executing in
the unmanaged code.

Take a look at this example:

http://msdn.microsoft.com/library/en-us/cpguide/html/cpcongchandlesample.asp?

This calls EnumWindows passing a delegate to a managed function, which is
the same scenario as you are describing.

Richard
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top