gpt4 book ai didi

linux - dotnet 核心中的 SocketCAN

转载 作者:太空宇宙 更新时间:2023-11-04 12:03:36 25 4
gpt4 key购买 nike

我正在为 Linux 上的设备编写软件,它应该可以与 CAN 接口(interface)一起使用。理想情况下,我希望在不连接来自 c++ 的第三方库的情况下使用该接口(interface)。可能吗?

最佳答案

我使用 native 函数解决了这个问题。这里示例绑定(bind)套接字,可以使用本地函数 write( 或 aio_write) 和 read 读写消息。 CanPublisher in UDSim例如

const int Siocgifindex = 0x8933;
private const int PfCan = 29;
private const int SockRaw = 3;
private const int CanRaw = 1;
private const int CanMtu = 16;

[DllImport("libc", SetLastError = true)]
private static extern int socket(int domain, int type, int protocol);
[DllImport("libc", SetLastError = true)]
private static extern int ioctl(int fd, int request, ref Ifreq mtu);
[DllImport("libc", SetLastError = true)]
private static extern int bind(int fd, ref SockaddrCan addr, int addrlen);


[StructLayout(LayoutKind.Sequential)]
struct SockaddrCan
{
public ushort can_family;
public int can_ifindex;
public uint rx_id;
public uint tx_id;
}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
struct Ifreq
{
public Ifreq(string ifr_name)
{
this.ifr_name = ifr_name;
this.ifr_ifindex = 0; // ifru_ivalue
this.ifru_mtu = 0;
}

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
public string ifr_name;
public int ifr_ifindex;
public uint ifru_mtu;
}

var addr = new SockaddrCan();
var s = socket(PfCan, SockRaw, CanRaw);
var ifr = new Ifreq("vcan0");
var ret = ioctl(s, Siocgifindex, ref ifr);
addr.can_ifindex = ifr.ifr_ifindex;
addr.can_family = PfCan;
ret = bind(s, ref addr, Marshal.SizeOf(addr));

关于linux - dotnet 核心中的 SocketCAN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51473139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com