C # Marshalled Callbacks

I am trying to use Marshall c call backs which are in structure. I am sure that everything is correct, but when using my C # example, I do not receive events, when using C ++ I get events.

Here is C #

class Program
{
    [DllImport("Some.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
    public static extern int SetCallbacks(Callbacks callBack);


    static Callbacks Callback = new Callbacks { DataArrived = DataArrived, SendFailure = SendFailure };
    static void Main(string[] args)
    {
        SetCallbacks(Callback);

        Console.ReadLine();
    }

    static void DataArrived(uint id, IntPtr data)
    {

    }

    static void SendFailure(uint id, uint id2, IntPtr data)
    {

    }
}



[StructLayout(LayoutKind.Sequential)]
public struct Callbacks
{
    public DataArrived DataArrived;
    public SendFailure SendFailure;
}

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void DataArrived(uint id,   IntPtr data);

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void SendFailure(uint id, uint id2, IntPtr ulpData);

This is from the header file C.

struct callBacks
{
    void (*dataArriveNotif) (unsigned int,    void*);
    void (*sendFailureNotif) (unsigned int, unsigned int, void*);
}

int SetCallbacks(callBacks callBacks);

Here is a working C ++.

struct callBacks;
callbacks.dataArriveNotif = &dataArriveNotif;
callbacks.sendFailureNotif = &sendFailureNotif;
SetCallbacks(callBacks);
+3
source share
2 answers

Everything about the delegate was really correct. I simplified senario a bit in this example.

public static extern int SetCallbacks(Callbacks callBack); 

was actually

public static extern int SetCallbacks(String[] array, Callbacks callBack);

The array of strings had many trailing 0s at the end. This caused the callback to structure all zeros. I gave up trying to arrange the string [] in the right way and just made it Intptr, and it all started.

+1
source

so very similar to this question asked yesterday ...

PInvoke #:

0

All Articles