Instantiating ion in GeneratePrimaries

Initial example is TestmEm0. If I use macro

/gun/particle ion
/gun/ion 6 12

and simply


in PrimaryGeneratorAction everything works fine.

But if I comment lines in macro file and want to use ion directly (pretty the same way what the macro file do looking the Messenger code):

fParticleGun->SetParticleDefinition(G4IonTable::GetIonTable()->GetIon(6, 12, 0));

than it fails and uses e- as default particle (e- is defined in SetDefaultKinematic of TestEm0).

What is the problem with setting ions directly in GeneratePrimaries?

I’m using Geant4.10.6-p02.

in example radioactivedecay/rdecay01, you will find :

G4int Z = 10, A = 24;
G4double ionCharge   = 0.*eplus;
G4double excitEnergy = 0.*keV;

G4ParticleDefinition* ion
   = G4IonTable::GetIonTable()->GetIon(Z,A,excitEnergy);

//create vertex

I’ve just coppied this entire part into of TestEm0 and it still don’t work (it sees e-).

As said in Readme, TestEm0 is a special exercice : there is no tracking. In particular, the function GeneratePrimaries( ) is never called.
A solution is to put commands in the main via the function ApplyCommand( ). For example, at end of :
UImanager->ApplyCommand("/gun/particle ion");
UImanager->ApplyCommand("/gun/ion 6 12");
UImanager->ApplyCommand("/run/beamOn 1");

I got the idea. Thank you for the explaination.