简体   繁体   中英

Calling C# Method from C++ via Delegates Results in Reversed Parameters

I am trying to have a C++ function call a method on a form in C# in order to update the GUI. For some reason, the function call from C++ sends the parameters in reversed order.

So the UpdateDROCallback() function gets 3.0 for the first parameter, 2.0 for the second, and 1.0 for the last when it was called with function(1.0, 2.0, 3.0).

What am I missing here?

[C#]

    public partial class Form1 : Form
    {
        delegate void DROUpdateDelegate(double x, double y, double z);
        DROUpdateDelegate m_DROUpdateDelegate;
        static DROUpdateDelegate s_DROUpdateDelegate;

        public Form1()
        {
            InitializeComponent();
            m_DROUpdateDelegate = new DROUpdateDelegate(UpdateDROCallback);
            s_DROUpdateDelegate = new DROUpdateDelegate(UpdateDRO);
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            int address = m_DROUpdateDelegate.Method.MethodHandle.GetFunctionPointer().ToInt32();
            TestDll.RegisterScaleUpdateCallback(address);
        }

        private static void UpdateDROCallback(double x, double y, double z)
        {
            s_DROUpdateDelegate(x, y, z);
        }

        private void UpdateDRO(double x, double y, double z)
        {
            BeginInvoke(
                new Action(
                    () =>
                    {
                        lblDROX.Text = x.ToString("0.0000");
                        lblDROY.Text = y.ToString("0.0000");
                        lblDROZ.Text = z.ToString("0.0000");
                    }));
        }
    }

TestDll.cs:

public static class TestDll
{
    (...)
    [DllImport("test.dll", EntryPoint = "RegisterScaleUpdateCallback")]
    public static extern void RegisterScaleUpdateCallback(int address);
    (...)
}

[C++]

StrobeTest.h:

#pragma once
class StrobeTest
{
    typedef void (__stdcall *DROUpdate)(double x, double y, double z);

private:
    static DROUpdate s_CallbackFunction;
public:
    StrobeTest(void);
    ~StrobeTest(void);

    static void InitializeStrobe(void);
    static void MoveXAtSpeed(double velocity);
    static void CALLBACK RegisterScaleUpdateCallback(DROUpdate function);
};

StrobeTest.cpp

(...)
void StrobeTest::RegisterScaleUpdateCallback(DROUpdate function)
{
    StrobeTest::s_CallbackFunction = function;
    StrobeTest::s_CallbackFunction(1.0, 2.0, 3.0);
}
(...)

Show the code of TestDll , especially the declaration of TestDll.RegisterScaleUpdateCallback in it. There will be the cause. Make sure that the calling conventions match.

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