答qdjdl 问:我在回调函数中想获取参数的值,如何实现?

来源:互联网 发布:猪八戒淘宝收藏有用吗 编辑:程序博客网 时间:2024/05/25 05:38

 c++ code:

 

static void (CALLBACK *fMessCallBack)(int *pBuf);

extern "C"
__declspec(dllexport)
void SetCallBack(void (CALLBACK *f)(int *pBuf))
{
    fMessCallBack = f;
}

extern "C"
__declspec(dllexport)
void CallCB()
{
 int a[2] = {2,3};
    (*fMessCallBack)(a);
}

c# code:

记得把项目属性->Build->Allow Unsafe Code勾上

然后:

using System;
using System.Runtime.InteropServices;

namespace ConsoleApplication1 {
    class Program {
        public unsafe delegate void fMessCallBack(int* pBuf);

        [DllImport("CppSample.dll")]
        public static extern void SetCallBack(fMessCallBack x);

        [DllImport("CppSample.dll")]
        public static extern void CallCB();

        public static void Main() {
            unsafe {
                fMessCallBack mC = new fMessCallBack(Ashley);
                SetCallBack(mC);
                CallCB();
            }

            Console.ReadLine();
        }

        public unsafe static void Ashley(int* pBuf) {
            int number1 = *pBuf++;
            int number2 = *pBuf;
            Console.WriteLine(number1);
            Console.WriteLine(number2);
        }
    }
}

原创粉丝点击