How to do alias to a C struct member?

dangbinghoo dangbinghoo at gmail.com
Tue Apr 23 02:41:22 UTC 2019


On Monday, 22 April 2019 at 15:50:11 UTC, dangbinghoo wrote:
> On Monday, 22 April 2019 at 13:10:45 UTC, Adam D. Ruppe wrote:
>> On Monday, 22 April 2019 at 11:04:49 UTC, dangbinghoo wrote:
>>> alias ifr_ifrn.ifrn_name	    ifr_name;	  /* interface name 	*/
>>>
>>> So, how to do alias for a C struct member?
>>
>>
>> D doesn't support this kind of alias. There's two options:
>>
>>
>>
>> Then you should be able to use it the same way as in C.
>
> OK, I'd prefer with option 2.
> thank you in advance!

hi all,

the correct answer is :

---
struct ifreq {
	private union ifr_ifrn_ {
		byte[IFNAMSIZ] ifrn_name; /* if name, e.g. "en0" */	
	}
	ifr_ifrn_ ifr_ifrn;

	private union ifr_ifru_ {
		sockaddr ifru_addr;
		sockaddr ifru_dstaddr;
		sockaddr ifru_broadaddr;
		sockaddr ifru_netmask;
		sockaddr ifru_hwaddr;
		short	ifru_flags;
		int	ifru_ivalue;
		int	ifru_mtu;
		ifmap ifru_map;
		byte[IFNAMSIZ] ifru_slave;	/* Just fits the size */
		byte[IFNAMSIZ] ifru_newname;
		byte * ifru_data;
	}
	ifr_ifru_ ifr_ifru;

	// NOTE: alias will not work : alias ifr_ifrn.ifrn_name	    
ifr_name;
	@property ref ifr_name() { return ifr_ifrn.ifrn_name; } /* 
interface name */
---

the `need this` error is telling that `ifr_ifrn` is not an 
instance but a type for my previous code.

so for C struct's union member, we need to first declare a member 
of that union type, and then using property to implement The 
C-Macro.


but here I have a question in further:

  As showing above, ifreq has a member of ``byte[IFNAMSIZ] 
ifrn_name;``, when translating the C style calling code, I need 
to do such a cast for D byte:

   ```
      strcpy(cast(char *)ifr.ifr_name.ptr, 
std.string.toStringz(if_name));
      if (ioctl(s, SIOCGIFHWADDR, &ifr) < 0)
      {
	    return;
      }
   ```
should I keep the `ifrn_name` to a `char[]` for avoid of doing 
cast D byte to C (char*) ? and I can calling like this:

   ```
struct ifreq {
	private union ifr_ifrn_ {
		char[IFNAMSIZ] ifrn_name; /* if name, e.g. "en0" */	
	}
   ...

      strcpy(ifr.ifr_name.ptr, std.string.toStringz(if_name));
      if (ioctl(s, SIOCGIFHWADDR, &ifr) < 0)
      {
	    return;
      }

   ```
this looks more clean and like the C style code.


--------------
Thanks!

Binghoo Dang



More information about the Digitalmars-d-learn mailing list