现在的位置: 首页 > 综合 > 正文

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

2012年01月05日 ⁄ 综合 ⁄ 共 904字 ⁄ 字号 评论关闭

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);
    }

 

抱歉!评论已关闭.