Question

Im trying to write a C# wrapper for Google's WebP encoder.

The method im trying to call is:

// Returns the size of the compressed data (pointed to by *output), or 0 if
// an error occurred. The compressed data must be released by the caller
// using the call 'free(*output)'.
WEBP_EXTERN(size_t) WebPEncodeRGB(const uint8_t* rgb,
                              int width, int height, int stride,
                              float quality_factor, uint8_t** output);

Borrowing from mc-kay's decoder wrapper I have come up with the following:

[DllImport("libwebp", CharSet = CharSet.Auto)]
public static extern IntPtr WebPEncodeRGB(IntPtr data, int width, int height, int stride, float quality, ref IntPtr output);

Unfortunately whenever I try to run this I get the following error:

A call to PInvoke function 'WebPSharpLib!LibwebpSharp.Native.WebPEncoder::WebPEncodeRGB' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.

I have tried many variations on the signature to no avail.

Anyone got a clue?

Cheers, Mike

Was it helpful?

Solution

Most likely cause for the error is that the C++ code uses cdecl calling convention but your pinvoke uses stdcall calling convention. Change the pinvoke as follows:

[DllImport("libwebp", CallingConvention=CallingConvention.Cdecl)]
public static extern UIntPtr WebPEncodeRGB(IntPtr data, int width, int height, 
    int stride, float quality, ref IntPtr output);

There's no need to specify CharSet for a function that has no text parameters. I also would use UIntPtr as the return type since size_t is unsigned.

There may be more problems with your code because we can't see how you are calling the function and we also don't know what the protocol is for calling it. You need to know more than the function signature in order to know how to call a function. However, I suspect that the calling convention problem will get you past your current hurdle.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top