We provide an integral formula for the free energy of the two-matrix model with polynomial potentials of arbitrary degree (or formal power series). This is known to coincide with the τ-function of the dispersionless two-dimensional Toda hierarchy. The formula generalizes the case of conformal maps of Jordan curves studied by Kostov, Krichever, Mineev-Weinstein, Wiegmann, Zabrodin and separately Takhtajan. Finally we generalize the formula found in genus zero to the case of spectral curves of arbitrary genus with certain fixed data.