The score was tied 1-1 with two out in the seventh when Castillo rocketed a 3-1 pitch from Giants starter Tim Lincecum deep into the left-field bleachers for his third homer of the year.
Cubs starter Travis Wood also socked a solo homer as Chicago got its first series sweep in San Francisco since September 1993.
Wood (7-7) surrendered just one unearned run on four hits over seven innings, overcoming four walks while striking out seven.
Pedro Strop threw a scoreless eighth and Kevin Gregg wrapped up the victory with his 22nd save.
Lincecum (5-11) struck out 10 but allowed two runs on four hits over seven full frames.
Pablo Sandoval produced the only RBI for San Francisco, which dropped a fourth straight overall.
Twerking Brooklyn burglar 'dropped it like it was hot' prior to theft
Video of Victoria’s Secret models trying to 'twerk' hits Instagram