Native interop fails with array of struct (libc.poll)
Hello
I have some code that calls libc.poll http://man7.org/linux/man-pages/man2/poll.2.html
[DllImport("libc.so.6", SetLastError = true)]
public static extern int poll( pollfd[] fds, int fdsCount, int timeout);
[Flags]
public enum POLL_EVENTS : ushort {
NONE = 0x0000,
POLLIN = 0x001,
POLLPRI = 0x002,
POLLOUT = 0x004,
POLLMSG = 0x400,
POLLREMOVE = 0x1000,
POLLRDHUP = 0x2000,
// output only
POLLERR = 0x008,
POLLHUP = 0x010,
POLLNVAL = 0x020
}
[StructLayout(LayoutKind.Sequential)]
public struct pollfd {
public int fd;
public POLL_EVENTS events;
public POLL_EVENTS revents;
}
// ...
pollfd fd = new pollfd( );
fd.fd = 0;
fd.events = POLL_EVENTS.POLLIN;
pollfd[ ] fds = new pollfd[ 2 ];
fds[ 0 ] = fd;
fds[ 1 ] = new pollfd( );
Libc.pipe( pipeFds );
fds[ 1 ].fd = pipeFds[ 0 ];
fds[ 1 ].events = POLL_EVENTS.POLLIN;
int nextwait = -1;
while ( true ) {
int pollRes = Libc.poll( fds, 2, nextwait );
File.AppendAllText("log", "pollRes=" + pollRes + "\n");
File.AppendAllText("log", "fds[0].revents=" + fds[0].revents + "\n");
File.AppendAllText("log", "fds[1].revents=" + fds[1].revents + "\n");
nextwait = -1;
}
I'm trying to run it in coreclr on Ubuntu 16.04 (x64) and always get POLLEVENTS.NONE instead of POLLEVENTS.POLLIN when keyboard was pressed. This code works well in Mono, so I think there is a bug in interop mechanism when dealing with array of structs.
@yizhang82 @fadimounir PTAL
@shrah Can you take a look?
@elw00d, according to msdn(https://msdn.microsoft.com/en-us/library/hk9wyw21(v=vs.110).aspx) array of structures with integers are marshalled as IN. So you wouldn't see the value changed by native Libc.poll from managed side. To get your desired behavior, you need to change your P/Invoke signature to:
[DllImport("libc.so.6", SetLastError = true)]
public static extern int poll([IN, OUT]pollfd[] fds, int fdsCount, int timeout);
Without looking into mono, my guess is mono treats array of blittable structs as [IN,OUT]
You are absolutely right ! Thank you very much !