关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

C#中如何C++动态库回调函数

发布时间:2020-01-19 17:12:12

1.C++动态库

导出函数定义

typedef void(__stdcall* fnCB)(int);

__declspec(dllexport)

void __stdcall TestCB(fnCB fn, int val)

{

fn(val);

}

注意:需要在.def文件中声明导出函数名称

20190315213409376.png


LIBRARY

EXPORTS

    TestCB


2.C#调用动态库函数


namespace ConsoleApp1

{

    class Program

    {

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]

        public delegate void del_fn(int val);

        //定义与DLL同名函数

        [DllImport("D:/test/ConsoleApp1/Debug/MFCLibrary1.dll", CallingConvention=CallingConvention.StdCall)]

        public static extern void TestCB([MarshalAs(UnmanagedType.FunctionPtr)] del_fn fn, int val);

        //重命名DLL导出函数

        [DllImport("D:/test/ConsoleApp1/Debug/MFCLibrary1.dll", CallingConvention = CallingConvention.StdCall, EntryPoint ="TestCB")]

        public static extern void DLL_TestCB([MarshalAs(UnmanagedType.FunctionPtr)] del_fn fn, int val);

        static void Main(string[] args)

        {

            TestCB(new del_fn(CB_Func), 10);

            DLL_TestCB(new del_fn(CB_Func), 20);

            System.Console.ReadKey();

        }

        public static void CB_Func(int val)

        {

            System.Console.WriteLine(val);

        }

    }

}


3.输出显示

20190315214113685.png



/template/Home/Zkeys/PC/Static