netcore-can-example icon indicating copy to clipboard operation
netcore-can-example copied to clipboard

Does not work on .Net 5

Open Peskind opened this issue 3 years ago • 3 comments

@jormenjanssen , I've built the project for .Net 5 (on the Torizon Ubuntu platform).

Both calls in the the function private Socket CreateSocketNetCore3_x(Type socketType, Type safeSocketType, string name) var socketConstructor = socketType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { safeSocketType }, null); var socketMethod = safeSocketType.GetMethod("CreateSocket", BindingFlags.NonPublic | BindingFlags.Static, null, new[] { typeof(IntPtr) }, null); returns null, so I can not create a socket for the "can0"

I've previously tried a simple C# porting from the article link, but there is only the write method implemented. In my project I have to write and listen for the messages from CAN bus.

Peskind avatar Apr 28 '21 14:04 Peskind

@Peskind I Will look into supporting this. Meanwhile you should be able to create the CAN socket with the following managed code

var socket = new Socket(AddressFamily.ControllerAreaNetwork, SocketType.Raw, ProtocolType.Raw);

This AddressFamily.ControllerAreaNetwork was previously not implemented on .Net Core but is now supported since 3.1

jormenjanssen avatar Apr 30 '21 08:04 jormenjanssen

@jormenjanssen Thank you,

I've inserted into public Socket CreateSocket(string adapterName)

            //.core 3.1+ and .net 5 supports CAN Sockets directly
            if ((Environment.Version.Major == 3 && Environment.Version.Minor>=1) || Environment.Version.Major > 3)
            {
                var socket = new Socket(AddressFamily.ControllerAreaNetwork, SocketType.Raw, ProtocolType.Raw);
                InitializeSocketCanForAdaper(socket.SafeHandle.DangerousGetHandle (), adapterName);
                return socket;
           }

and it work.s

Peskind avatar Apr 30 '21 11:04 Peskind

@Peskind Thanks for this code, was exactly what I was looking for.

Given that .NET 3.0 and below aren't even officially supported anymore, does it make sense to change SocketCanFactory.CreateSocket() to drop support for .NET Core 2.X-3.0, and simply use new Socket(AddressFamily.ControllerAreaNetwork, SocketType.Raw, ProtocolType.Raw); always?

crozone avatar Mar 25 '22 03:03 crozone