I am working on a C++ application that integrates with Node.js using the N-API (via napi) / node_api.h, where I expose C++ classes and methods to JavaScript. Specifically, I have a TEAM class with a vector of CTF_player objects, and I want to fetch a player’s name using the GetPlayerName method.
Here’s what’s happening:
The first call to GetPlayerName works fine and returns the expected result.
However, when I try to call the same method again, nothing happens after that point, and no errors are thrown.
I suspect there may be an issue with memory management or accessing the vector of CTF_player objects (members[index]).
class CTF_player
{
private:
std::string name;
int score;
public:
// Constructor
CTF_player(const std::string &playerName, int playerScore)
: name(playerName), score(playerScore) {}
// Getter for name
std::string getName() const
{
return name;
}
// Getter for score
int getScore() const
{
return score;
}
// Setter for name
void setName(const std::string &newName)
{
name = newName;
}
// Setter for score
void setScore(int newScore)
{
score = newScore;
}
};
class TEAM
{
public:
std::vector<CTF_player> members;
std::string GetPlayerName(int index)
{
if (index < 0 || index >= members.size())
{
return ""; // Handle out-of-bounds case
}
return members[index].getName();
}
void addMember(const CTF_player &player)
{
members.push_back(player);
}
};
napi_value GetPlayerName(napi_env env, napi_callback_info info)
{
// Arguments parsing
size_t argc = 2;
napi_value args[2];
napi_status status = napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
TEAM *team;
napi_get_value_external(env , args[0] , (void**)&team);
int index;
status = napi_get_value_int32(env, args[1], &index);
std::string name = team->GetPlayerName(index);
napi_value js_name;
napi_create_string_utf8(env, name.c_str(), name.size(), &js_name);
return js_name;
}
let team1 = CreateCTF_TEAM("Team A", 1);
console.log("Team created:", GetTeamName(team1));
CreateCTFPlayer("bilal" , 1 , team1);
console.log("p1" , GetPlayerName(team1 , 0));
//after this the rest of the code is skipped
console.log("p1" , GetPlayerName(team1 , 0));
let team2 = CreateCTF_TEAM("Team B", 1);
console.log("Team created:", GetTeamName(team2));
After the first call to GetPlayerName, the subsequent calls do not return the expected result, and it seems that nothing happens after the second call.
I suspect that the problem might be related to the std::string handling or how the C++ object is being managed in memory between JavaScript calls.
Could the memory management (via napi_create_external) or vector indexing be causing issues?
How can I ensure that the objects remain valid and accessible between calls in Node.js?
I would appreciate any advice on how to solve this issue or where to look further.