简体   繁体   中英

How to declare a delegate in C++/cli and use it in C#

I have a C++/cli class library that wraps some native code. Everything works great, and I am writing C# code for testing and usage examples. One of the C++ methods does processing on a file (can take some time) so I want to use a callback function to report progress to the C# caller. I have declared a delegate in C++ library as follows:

public delegate int ProcListCB(int state, int status, long count);

and a function for setting the delegate from code using the library as follows:

public ref class MyClass
{
    public:
    void SetProcListCallback(ProcListCB ^ cb)
    { 
        HouseKeeping::procListCallback = cb;
    }
};

In C#, I have the following:

    ProcListCB procListCB;

    public int ProcessListCallback(int state,int status,long count)
    {
        int rtnVal = 0;
        // some code...
        return (rtnVal);
    }

    private void Process_Click(object sender, EventArgs e)
    {
        VerifySq vsq = new VerifySq();
        ProcListCB cb = new ProcListCB(ProcessListCallback);
        vsq.SetProcListCallback(cb);
        ...
    }

I'm getting a compile error:

error CS0123: No overload for 'VerifySqListGui.MainWin.ProcessListCallback(int, int, long)' matches delegate 'AccuMailCoreVerifySq.ProcListCB'

I've searched for awhile, and I haven't found an answer (obviously). I assume there is some function calling convention mismatch, but I don't know the details. Any help would be appreciated...

public delegate int ProcListCB(int state, int status, long count);

If you're doing this in C++/CLI, then the issue is the C++ datatypes. How big is a C++ int ? 32 bits. How big is a C++ long ? Also 32 bits.

Since you're going for interoperability with C#, I'd use the C# datatypes explicitly. (And yes, even if you have a using namespace System; , I'd still use System:: on this line, to make it blazingly obvious that you're referencing the .Net types.)

public delegate System::Int32 ProcListCB(
    System::Int32 state, System::Int32 status, System::Int64 count);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM