Amir Jan, a driver who had been washing his car near the consulate, said he saw three men with Kalashnikov assault rifles move toward the consulate around 9:15 a.m. He said one threw a grenade before they all opened fire.

Officials later said that two Pakistani civilians, a father and son who had come from Quetta to get Chinese visas, were also killed in the attack.

Prime Minister Imran Khan issued a statement on Twitter insisting that such attacks could not shake the relationship between China and Pakistan. He said the strike had clearly been intended “to scare Chinese investors” and came as a result of trade agreements announced during his trip to China this month.

The Chinese Embassy in Islamabad, the capital, later issued a statement extending condolences over the deaths and expressing faith in Pakistani security. “We believe that the Pakistani side is able to ensure the safety of Chinese institutions and personnel in Pakistan,” the statement said, adding that any attempt to undermine the countries’ relationship was “doomed to fail.”

After the attack in Karachi, another bombing — this one in the Orakzai region of northwestern Pakistan — showed the continuing threat posed by militants on a separate front.

At least 30 people were killed and 40 or more wounded when a bomb blast ripped through a fruit and vegetable market in the Hangu district there, officials said. The market was near a seminary for Shiite Muslims, a minority in Pakistan that is frequently targeted by extremist Sunni groups.

“The dead include Sunnis, Shiites and a couple of Sikh community members,” said a local official, Mutahir Zeb Khan. “We are identifying the dead.”