SocketCANSharp icon indicating copy to clipboard operation
SocketCANSharp copied to clipboard

The api in the class LibcNativeMethods are bloated

Open Vincent-X-Zhang opened this issue 9 months ago • 1 comments

The api in the class LibcNativeMethods such as:

        /// <summary>
        /// Write the BcmCanFdMessage to the socket. Variant for 32-bit.
        /// </summary>
        /// <param name="socketHandle">Socket Handle Wrapper Instance</param>
        /// <param name="message">BCM Message to write</param>
        /// <param name="msgSize">Size of BCM Message in bytes</param>
        /// <returns>The number of bytes written on success, -1 on error</returns>
        [DllImport("libc", EntryPoint="write", SetLastError=true)]
        public static extern int Write(SafeFileDescriptorHandle socketHandle, BcmCanFdMessage32 message, int msgSize);

        /// <summary>
        /// Write the BcmCanSingleMessage to the socket. Variant for 32-bit.
        /// </summary>
        /// <param name="socketHandle">Socket Handle Wrapper Instance</param>
        /// <param name="message">Special Single Frame BCM Message to write</param>
        /// <param name="msgSize">Size of BCM Message in bytes</param>
        /// <returns>The number of bytes written on success, -1 on error</returns>
        [DllImport("libc", EntryPoint="write", SetLastError=true)]
        public static extern int Write(SafeFileDescriptorHandle socketHandle, BcmCanSingleMessage32 message, int msgSize);

They actually are the same native api:

ssize_t write(int fd, const void* buf, size_t count);

I mean, maybe there is a better way to unify them?

Vincent-X-Zhang avatar Apr 17 '25 14:04 Vincent-X-Zhang

Your observation is 100% correct. The reason why I provide so many overloads is to allow the .NET marshaller to do most of the heavy lifting for us.

In most cases, it was/is indeed possible to provide a single P/Invoke method signature per native function which takes a generic IntPtr parameter, but then we would need to call Marshal.AllocHGlobal(), Marshal.StructureToPtr() and Marshal.FreeHGlobal() many times over and over again. While it is more code regarding P/Invokes method signatures, it is less code everywhere else. In addition, using the Marshal methods incorrectly can lead to memory leaks and so the less of that we have the safer our code will be.

derek-will avatar Apr 22 '25 04:04 derek-will