Implement callback C# functions for C++ DLL

后端 未结 4 1461
攒了一身酷
攒了一身酷 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 17:08

    As it turns out, the answer to the original question is rather simple, once you know it, and the whole callback issue was no issue. The input buffer parameter is replaced with parameter pair unsigned char *input, int input_length, and the output buffer parameter is replaced with parameter pair unsigned char **output, int *output_length. The C# delegate should be something like this

    public delegate int CallbackDelegate(byte[] input, int input_length,
                                         out byte[] output, out int output_length);
    

    And wrapper in C++ should be something like this

    void FunctionCalledFromLib(const std::vector& input, std::vector& output)
    {
        unsigned char *output_aux;
        int output_length;
    
        FunctionImplementedInCSharp(
            &input[0], input.size(), &ouput_aux, &output_length);
    
        output.assign(output_aux, output_aux + output_length);
    
        CoTaskMemFree(output_aux); // IS THIS NECESSARY?
    }
    

    The last line is the last part of the mini-puzzle. Do I have to call CoTaskMemFree, or will the marshaller do it for me automagically?

    As for the beautiful essay by plinth, I hope to bypass the whole problem by using a static function.

提交回复
热议问题