【问题标题】:Calling C++ DLLs from C# ESP value从 C# ESP 值调用 C++ DLL
【发布时间】:2012-05-26 07:05:34
【问题描述】:

所以我有一个用 C++ 制作的 DLL,我在 C# 中使用它。问题是我在 C++ 中使用了函数指针,所以我做了一个委托。孔程序可以工作,但完成后我收到一个消息框,指出 ESP 的值没有为函数保存。

我的代码: C++ DLL

typedef void (*FUNCTION_TYPE)(bool);
extern "C"
{
    DLL void prim(int a, FUNCTION_TYPE myF)
    {
        if(a < 2)
        {
            myF(false);
            return;
        }

        for (int i = 2; i < a; i++)
        {
            if (a % i == 0)
            {
                myF(false);
                return;
            }
        }

        myF(true);
    }
};

我的 C# 代码(调用 dll):

delegate void SOME_FUNCTION(bool isFine);

        [DllImport("DLLs")]
        private static extern void prim(int n, SOME_FUNCTION afisare);

        static void afisare(bool isFine)
        {
            if (isFine == true)
                Console.WriteLine("Da, e prim");
            else
                Console.WriteLine("Nu, nu e prim");
        }

        static void Main(string[] args)
        {
            SOME_FUNCTION myAfis = afisare;
            prim(17, myAfis);
        }

【问题讨论】:

    标签: c# c++ dll delegates function-pointers


    【解决方案1】:

    您的调用约定不匹配。 C++ 函数指针类型使用cdecl。托管代码采用stdcall。像这样修复它:

    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    delegate void SOME_FUNCTION(bool isFine);
    

    或者,您可以将 C++ 代码中的调用约定更改为 stdcall

    typedef void (__stdcall *FUNCTION_TYPE)(bool);
    

    但请确保您只做其中一项,而不是两者都做!

    【讨论】:

    • 非常感谢!当我被允许时,我会接受你的回答:D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多