• C#传委托给C的函数指针调用问题


    C代码如下:

    #include "stdio.h"

    __declspec(dllexport) int Call(int (*qq)(int num),char * str)
    {    
        printf(str);
        return qq(123);
    }
    多次验证发现在C#中传委托给C中的函数指针,如果委托不带参数则都能成功运行,但是委托一带参数不管是int参数还是string参数或者其他参数,都会报“ 尝试读取或写入受保护的内存。这通常指示其他内存已损坏的错误,找了一天才找到解决方法,既在C#的委托声明上加[UnmanagedFunctionPointer(CallingConvention.Cdecl)],正确调用如下:

     [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
        public delegate int MyDeg(int num);
        class Program
        {
            static void Main(string[] args)
            {
                
                try
                {
                    MyDeg myd = new MyDeg(FF);
                    Console.WriteLine(Call(myd, "helloworld"));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

            }

            static int FF(int num)
            {
                Console.WriteLine(num);
                return num + 1;

            }

            [DllImport("my.dll", EntryPoint = "Call")]
            public extern static int Call(MyDeg mm ,string  str);
        }
  • 相关阅读:
    BZOJ 1150 [CTSC2007]数据备份Backup(贪心+优先队列)
    BZOJ 1053 [HAOI2007]反素数ant(约数个数)
    BZOJ 1066 [SCOI2007]蜥蜴(最大流)
    CodeForces 772A Voltage Keepsake
    HDU 6030 Happy Necklace
    HDU 6031 Innumerable Ancestors
    HDU 6026 Deleting Edges
    HDU 6024 Building Shops
    HDU 6029 Graph Theory
    HDU 6025 Coprime Sequence
  • 原文地址:https://www.cnblogs.com/mxw09/p/1829311.html
Copyright © 2020-2023  润新知