Implement callback C# functions for C++ DLL

后端 未结 4 1463
攒了一身酷
攒了一身酷 2021-02-06 16:29

I\'m writing a DLL wrapper for my C++ library, to be called from C#. This wrapper should also have callback functions called from the library and implemented in C#. These functi

4条回答
  •  无人共我
    2021-02-06 16:44

    There is no point to using C++/cli.

    And here is a real world example from my project.

    public ImageSurface(byte[] pngData)
        : base(ConstructImageSurfaceFromPngData(pngData), true)
    {
        offset = 0;
    }
    
    private static int offset;
    
    private static IntPtr ConstructImageSurfaceFromPngData(byte[] pngData)
    {
        NativeMethods.cairo_read_func_t func = delegate(IntPtr closure, IntPtr out_data, int length)
        {
            Marshal.Copy(pngData, offset, out_data, length);
            offset += length;
            return Status.Success;
        };
        return NativeMethods.cairo_image_surface_create_from_png_stream(func, IntPtr.Zero);
    }
    

    That is used to transfer PNG data from C# to the native cairo API.

    You can see how the C function pointer cairo_read_func_t is implemented in C# and then used as a callback for cairo_image_surface_create_from_png_stream.

    Here is a similar example.

提交回复
热议问题