def coresight_write(self, reg, data, ap=True):
        """Writes an Ap/DP register on a CoreSight DAP.

        Note:
          ``coresight_configure()`` must be called prior to calling this method.

        Args:
          self (JLink): the ``JLink`` instance
          reg (int): index of DP/AP register to write
          data (int): data to write
          ap (bool): ``True`` if writing to an Access Port register, otherwise
            ``False`` for Debug Port

        Returns:
          Number of repetitions needed until write request accepted.

        Raises:
          JLinkException: on hardware error
        """
        ap = 1 if ap else 0
        res = self._dll.JLINKARM_CORESIGHT_WriteAPDPReg(reg, ap, data)
        if res < 0:
            raise errors.JLinkException(res)
        return res