itzjackyscode
itzjackyscode

Reputation: 1084

How does C# handle passing null delegates to a native function?

Suppose a C library (let's call it mylib.so) exposes the following:

typedef void (*EventCallback)(int);

// there would be an additional declspec macro'd in here
// macro'd in here on Windows
void AddEventHandler(EventCallback ec);

In C#, I then use mylib.so like this:

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate void EventCallback(int type);

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate void AddEventHandlerFn(EventCallback? ec);

// later in some code ...

IntPtr libHandle = NativeLibrary.Load("mylib.so");
var addEventHandler = Marshal.GetDelegateForFunctionPointer<AddEventHandlerFn>(
  NativeLibrary.GetExport(libHandle, "AddEventHandler")
);

addEventHandler(null);

When I call addEventHandler(null) in C#, do I get (EventCallback) 0 in the C function? If not, what actually happens?

Upvotes: 0

Views: 198

Answers (1)

itzjackyscode
itzjackyscode

Reputation: 1084

Running a small test project, I found that the behaviour I expected (null delegates becoming null function pointers) to be true.

Upvotes: 1

Related Questions