Pass callback argument from C# to unmanaged C++

c#, c++, marshalling

Solution

It is because you MUST put the `ref` modifier before the argument and that forces the it to be a variable. so:

change you extern to:

public static extern Byte someMethod([MarshalAs(UnmanagedType.FunctionPtr)] 
                            ref SomeDelegate pDelegate);

and your call to:

        SomeDelegate action = new SomeDelegate(myCallback);
        someMethod(ref action);

UPDATE: And if you want to pass an argument to the callback (say an int):

public delegate Byte SomeDelegate([MarshalAs(UnmanagedType.I4)] int value);

[DllImport("mylibraryname.dll")]
public static extern Byte someMethod([MarshalAs(UnmanagedType.FunctionPtr)]
                                       ref SomeDelegate pDelegate);

Byte MyMethod([MarshalAs(UnmanagedType.I4)] int value)
{
    return (byte) (value & 0xFF);
}

and calling:

SomeDelegate action = new SomeDelegate(MyMethod);
someMethod(ref action);

Problem

I have some of unmanaged C++ dynamic library and C# GUI application, using it. I want to pass callback via parameters in some library provided methods. Is it possible to pass a callback to unmanaged C++ method from C#. ``` // unmanaged C++ typedef uint8_t (__stdcall *SomeCallback)(); MYDLL_API uint8_t someMethod(SomeCallback cb); ``` I'm trying to use library in this way: ``` // C# part public delegate Byte SomeDelegate(); [DllImport("mylibraryname.dll")] public static extern Byte someMethod(ref SomeDelegate pDelegate); // actuak callback Byte myCallback() { // some code } ... // call unmanaged passing callback static void Main(string[] args) { someMethod(myCallback); } ``` I receive error on compilation: ``` cannot convert from 'method group' to 'ref SomeDelegate ``` Am I totally wrong with my approach?

Original source