Need help with converting C struct containing function pointers to C#

T

Thomas Connolly

Hello list,
No one seems to be replying to my request on the interop group so I thought I would try here.
Can someone please help me with this? I have a C struct containing function pointers like so:

typedef struct _tagLiffeResponseHandlerList
{

void (*OnAccessTransfer) (LiffeStatus eStatus, const char* pszTrader, LiffeBoolean bContinuationFlag,
int nNumOrders, const LiffeOrderEntryList* pcLiffeOrderEntryList, time_t nTimeStamp);

****** other function pointers omitted for brevity *******

} LiffeResponseHandlerList;

Would the following be correct?

public delegate void OnAccessTransfer(LiffeStatus eStatus, [MarshalAs(UnmanagedType.LPStr)] string pszTrader, LiffeBoolean bContinuationFlag, int nNumOrders, ref LiffeOrderEntryList pcLiffeOrderEntryList, uint nTimeStamp);

[StructLayout(LayoutKind.Sequential)]
public class LiffeResponseHandlerList
{
public OnAccessTransfer OnAccessTransfer;
}

Thanks for the help
 
N

Nicholas Paldino [.NET/C# MVP]

Thomas,

That looks fine, the only thing is that I think that you ^might^ have to
add the MarshalAs attribute for the pointer itself, like this:

[StructLayout(LayoutKind.Sequential)]
public class LiffeResponseHandlerList
{
[MarshalAs(UnmanagedType.FunctionPtr)]
public OnAccessTransfer OnAccessTransfer;
}

I'm not sure if delegates are marshaled like this by default (although I
would assume they are). Also, if something is setting this structure up,
(assining the function pointer and returning it), I am not sure if .NET will
marshal it back correctly. I think in 2.0 it will do it correctly, while I
am unsure about 1.1 and before (it's easy enough to test).

Hope this helps.
 
B

Brian Brown

Nicholas said:
Thomas,

That looks fine, the only thing is that I think that you ^might^ have to
add the MarshalAs attribute for the pointer itself, like this:

[StructLayout(LayoutKind.Sequential)]
public class LiffeResponseHandlerList
{
[MarshalAs(UnmanagedType.FunctionPtr)]
public OnAccessTransfer OnAccessTransfer;
}

So the million dollar question (For me)... is there any way to do this
in the compact framework, since MarshalAs doesn't exist (among other
things...)?

:)

Brian
 
B

Bruce Wood

The other million-dollar question, Thomas, is are you trying to pass
data back and forth between C and C#, and so need to reproduce the
structure exactly, or are you trying to translate a program from C to
C#, and so want to reproduce the behaviour.

I assume from the fact that you posted to the interop group to start
with that it's the former. If it's the latter then there's probably a
whole other way to go about this in C#.
 

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