Quantcast
Channel: Common Language Runtime Internals and Architecture forum
Viewing all articles
Browse latest Browse all 1710

Using PInvoke with function pointer and delegate

$
0
0
Hi,

I'm trying to implement the right definition in C# for the following C code from the FFmpeg shared library:
void av_log_set_callback (void(*)(void *, int, const char *, va_list) callback)

As its name fully explains, the function set a user callback function to be called when something is written in the log.
Among the parameters there's a string (const char *) that must be formatted with a variable list of variant arguments (va_list).

My C# implementation is this:

public delegate void SetCallbackDelegate(IntPtr ptr, int level, string fmt, params object[] vargs);

[DllImport(DLL_NAME, SetLastError = true)]
public static extern void av_log_set_callback([MarshalAs(UnmanagedType.FunctionPtr)] SetCallbackDelegate callback);

av_log_set_callback(new SetCallbackDelegate(LogCallback);

private void LogCallback(IntPtr ptr, AVLogLevel level, string fmt, params object[] vargs)
{
// do something here
}

At runtime, whenever the callback function is being called, I got this error:

InvalidVariant was detected
Message: An invalid VARIANT was detected during a conversion from an unmanaged VARIANT to a managed object. Passing invalid VARIANTs to the CLR can cause unexpected exceptions, corruption or data loss.


The problem is the last parameter, the va_list.
Googlin' around I've found some posts that show some undocumented features of C#, including __arglist, that seems to be the right thing to use, but is not possible in a delegate definition.
If I replace 'params object[]' with 'string[]' everything works fine, but the arguments aren't always strings.

How should I do?

Thanks in advance

Marco

Viewing all articles
Browse latest Browse all 1710

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>