C# Interface to C DLL Interface Design Questions

J

jkimmel

I am having trouble designing an interface between the managed and
unmanaged layers of an application I'm writing.

My application has two parts. A C DLL that generates key/value pairs
(the same 300 keys have new values 10 times a second), and a C#
application that processes those values. Some metadata gets generated
every update as well. The DLL must be unmanaged C.

My question is, how should I transfer the values from the C DLL to the
C# app? A hashtable seems like the obvious choice, but I don't know
that one can be marshaled. Should I register a list of keys I'm
interested in with the C DLL, and then use a structure to get back the
values (as an array), plus the metadata?

And how do I notify the C# application that new data has arrived? A
callback is my first inclination, though from googling it sounds like
callbacks to unmanaged code is hard in .NET. Polling or some type of
messaging system are the only other alternatives I see, and I'm
worried I'll miss update cycles with those.

Another thing to consider is this C DLL may need to be used in a matlab
application as well. I don't know much about matlab programming, but
does this limitation preclude me from using callbacks (or any of your
suggestions)?

Any help/suggestions would be greatly appreciated. Thank you.

J. Kimmel
 
N

Nicholas Paldino [.NET/C# MVP]

J.,

First, I am curious, why must the DLL be in unmanaged C?

I'm not sure about matlab, to be honest, so I can't say whether or not
what I will propose will work.

However, you could write your component as a .NET component, then expose
it to COM, so unmanaged code can access it (matlab, and maybe fufill the
requirement that unmanaged code access it, which is why you might have said
the dll has to be in unmanaged code).

If you really can't write it in .NET, you could define a function
definition which you could duplicate in .NET through a delegate. When you
make the call to your functions in your DLL, then you can pass the delegate
in, and store it in the dll, calling it when there is an update.

So basically, you would have a method which takes the fields you want
notifications of, as well as a callback. Then, your dll would store the
function pointer (that's what it will look like to it) and then call it when
there is an update. On the .NET side, you have to make sure the object
instance that the method that the delegate refers to doesn't go out of scope
so it is not collected, and you don't have a memory access violation when
your unmanaged code calls back into managed code.

Hope this helps.
 

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

Top