zoukankan      html  css  js  c++  java
  • 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);
        }
  • 相关阅读:
    手动安装vue-devtools
    redis随记
    JS时间格式化
    360自动抢票还不够,几行js代码设置无人值守
    HttpWebRequest请求返回非200的时候 HttpWebResponse怎么接受返回错误提示
    android发编译
    asprise-ocr-api-sample 高价收破解版64 32位
    (16)集合操作
    (15)字典操作
    (14)字符串
  • 原文地址:https://www.cnblogs.com/mxw09/p/1829311.html
Copyright © 2011-2022 走看看