Can not read table

While trying to FindParticle in table, particle returns 0 because the table in not initialized. How can this be done?

// Geant4 example: extended/electromagnetic/TestEm18/src/
#include “G4ParticleTable.hh”
#include “G4ParticleDefinition.hh”

G4ParticleDefinition* particle = G4ParticleTable::GetParticleTable()->FindParticle(“alpha”);
G4double particle_mass = particle->GetPDGMass();
G4bool particle_stable = particle->GetPDGStable();

What Geant4 version is this with? Have you tried setting up the particle gun via scripting commands as shown in edep.mac? It should be possible to do change the line in that to

/gun/particle alpha

this is for a custom gun so I would like to read the table inside my functions to query the mass, because I want to use the mass defined in geant4 to avoid issues. What is edep.mac? I don’t find any information on that.

The code linked seems to be, or modified from, that in extended/electromagnetic/TestEm18. That comes with edep.mac:

Can you share the rest of the code? How are you setting up the run manager and gun/physics/detector and any other actions?

I think that is probably the problem, I don not know how to set up the necessary requirements to load the table. My code has this function to get the mass which is used inside a function to generate a .hepmc file.

double get_mass(int pid) {
    std::map<int, std::string> myMap;
    myMap[211] = "pi+";
    myMap[-211] = "pi-";
    myMap[2212] = "neutron";
    myMap[2112] = "proton";
    myMap[111] = "pi0";
    myMap[130] = "kaon0L";
    G4double particle_mass1 = -1.;
    std::string  particle_name = myMap[pid];
    std::cout<<"particle_name: "<< particle_name <<"\n";
    double particle_mass = 0.0;
    G4ParticleTable*      table = G4ParticleTable::GetParticleTable();
    G4ParticleDefinition* particle = table->FindParticle("opticalphoton");
    if (0 == particle) {
        std::cout<<"got particle: "<< particle <<"\n";
    // std::cout<<"got particle: "<< particle <<"\n";
    // particle_mass1 = particle->GetPDGMass();
    // std::cout<<"particle_mass: "<< particle_mass1 <<"\n";
    return particle_mass;

If all you are needing is the particle definitions, then they can either be accessed directly, e.g.

#include "G4GammaDefinition.hh"
auto def = G4Gamma::GammaDefinition();

Or if you want to use the particle table, include and use the “constructors” for each category, e.g.

// Replace "Boson" with "Lepton", "Baryon", "Meson" and "Ion" for the others
#include "G4BosonConstructor.hh"

Calling these before you access the particle table should populate it correctly.