Register Callback function to C++ DLL from C#

H

Henrik Pedersen

Hi

I am developing a wrapper for a C++ SDK DLL built for a video capture
card. After opening all channels on the card i call the function
StartVideoCapture(IntPtr channelHandle) what is supposed to happen after
that is that when the data stream is reday the DLL should raise an event
through a callback that i have registerd with the DLL. In that function
i can then access the data stream. The problem is just that the C++ Dll
uses void* pointers and i haven´t got the slightest clue on how to
Marshal that. I have the full source code of a C++ demo project and all
the DLL specifications. The function specs in the DLL lokks like this:

1.
typedef int (*STREAM_DIRECT_READ_CALLBACK)(ULONG channelNumber,void
*DataBuf,DWORD Length,int FrameType,void *context);

2.
DLLEXPORT_API int __stdcall
RegisterStreamReadCallback(STREAM_READ_CALLBACK StreamReadCallback, void
*Context);


I have tried with something like this but with no luck.

public delegate short STREAM_DIRECT_READ_CALLBACK( uint
channelNumber,[MarshalAs(UnmanagedType.IUnknown)]object DataBuf,uint
Length,int FrameType,[MarshalAs(UnmanagedType.IUnknown)]object Context);

[DllImport("DsSdk.dll", CharSet=CharSet.Ansi)]
public static extern short
RegisterStreamDirectReadCallback(STREAM_DIRECT_READ_CALLBACK
StreamDirectReadCallback,[MarshalAs(UnmanagedType.IUnknown)]object
Context);

And then:
RegisterStreamDirectReadCallback(new
STREAM_DIRECT_READ_CALLBACK(this.StreamDirectReadCallback),
this.Handle);

But it keeps crashing hard every time i try to run it.
I have struggeld with this for a while now and desperatly need help..


/Henrik Pedersen
Sweden
 
N

Nicholas Paldino [.NET/C# MVP]

Henrik,

Your delegate should look like this:

public delegate int STREAM_DIRECT_READ_CALLBACK(
uint channelNumber,
IntPtr DataBuf,
uint Length,
int FrameType,
IntPtr Context);

And your method declaration to register the callback should look like
this:

[DllImport("DsSdk.dll", CharSet=CharSet.Ansi)]
public static extern int RegisterStreamDirectReadCallback(
STREAM_DIRECT_READ_CALLBACK StreamDirectReadCallback,
IntPtr Context);

Basically, void pointers are marshaled as IntPtr instance. Of course,
this means that you have to marshal whatever you want to pass yourself. If
you know that the context is always going to be of a more particular type,
then you can be more specific with the declaration.

Also, int in C++ marshals as an int in .NET.

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