Gallardo earlier in the week was arrested for drunken driving, registering 0.22 on a blood alcohol test, which is nearly three times the Wisconsin state legal limit. He issued a lengthy apology Wednesday.
In his first outing since the arrest, Gallardo allowed one run while walking one and striking out six and improved to 1-1.
Gallardo's home run, which came after an RBI single from Yuniesky Betancourt, was a two-run shot over the fence in left-center that put the Brewers up 5-0 in the second inning. It was his 11th home run of his career.
Jonathan Lucroy added a two-run home run in the third for Milwaukee as Cain allowed seven runs -- all earned -- on seven hits in six innings.
Brandon Belt had a sacrifice fly in the fourth that got the Giants on the board and Brandon Crawford had a ninth-inning home run that completed the scoring.
Caroline Berg Eriksen: Soccer player's wife triggers debate with post-birth selfie
Exploding whale video goes viral on Internet