Delegate struct

A

Aviram Gilboa

Hi,

I have the following code defined:

<StructLayout(LayoutKind.Sequential)> Public Structure Callbacks
<MarshalAs(UnmanagedType.FunctionPtr)> Public OnError As
OnErrorDelegate
<MarshalAs(UnmanagedType.FunctionPtr)> Public OnConnect As
OnConnectDelegate
End Structure

Dim pShuttleCallbacks As USTradeShuttleCallbacks
pCallbacks.OnConnect = New OnConnectDelegate(AddressOf OnConnect)
pCallbacks.OnError = New OnErrorDelegate(AddressOf OnError)
.....

and the "On..." fintion definitions.

when I call a function in my Unmanaged code in c++ with the callbacks
struct I get an NullReferenceException error, do I have to define
something to keep the delegate ?
 
K

Ken Tucker [MVP]

Hi,

Had a similar problem with a callback function. It would work the
first time and forget where to go for the second. I created a form level
variable of the delegate type and used that in the structure.

Ken
--------------
Hi,

I have the following code defined:

<StructLayout(LayoutKind.Sequential)> Public Structure Callbacks
<MarshalAs(UnmanagedType.FunctionPtr)> Public OnError As
OnErrorDelegate
<MarshalAs(UnmanagedType.FunctionPtr)> Public OnConnect As
OnConnectDelegate
End Structure

Dim pShuttleCallbacks As USTradeShuttleCallbacks
pCallbacks.OnConnect = New OnConnectDelegate(AddressOf OnConnect)
pCallbacks.OnError = New OnErrorDelegate(AddressOf OnError)
.....

and the "On..." fintion definitions.

when I call a function in my Unmanaged code in c++ with the callbacks
struct I get an NullReferenceException error, do I have to define
something to keep the delegate ?
 
M

mef526

This is because the delegate is actually a variable and when it goes out of
scope it is gone. It needs to have a longer life. Declare it as static in
the procedure or at the form level so that it does not go out of scope and
get GC'd
 

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