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);
        }
  • 相关阅读:
    Golang 版本 支付宝支付SDK app支付接口2.0
    用 Certbot-auto 在 letsencrypt.org申请免费 SSL 证书实现 HTTPS
    Go类型断言demo
    签名算法
    golang cron定时任务简单实现
    Chapter Zero 0.2.2 内存
    Linux-系统目录结构
    Linux-关于Bash
    Chapter Zero 0.2.1 执行运算与判断的CPU
    Chapter Zero 0.1.4 计算机上常用的计算单位
  • 原文地址:https://www.cnblogs.com/mxw09/p/1829311.html
Copyright © 2011-2022 走看看