Click here to Skip to main content
15,566,691 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi, all.
I am starting napi. I'm trying to get struct data created in c into javascript, but I can't find a way for the struct.
The return int value is corrent. But Struct doesn't.
Tried Napi::Object. But it doesn't work.
Please let me know if there are other things to consider

The principle is that if you send a number from the web to ajax, Napi will
It finds that file, loads it into a list and passes the data.

What I have tried:

Function has a problem.
#include <napi.h>

..
Napi::Value ClassExample::GetFile(const Napi::CallbackInfo &info)
{
  Napi::Env env = info.Env();
  Napi::HandleScope scope(env);

  if (info.Length() != 1 || !info[0].IsNumber())
  {
    Napi::TypeError::New(env, "Number expected").ThrowAsJavaScriptException();
  }
  Napi::Number n = info[0].As<Napi::Object>();

 // Here, openFile function return struct!
  Napi::Object obj = this->actualClass_->openFile(n).width;  << error
  return Napi::Object::New(info.Env(), Obj);
}


The code below shows what happens when it returns a number.When return int value, no problem.
Of course, at this time, the getfile function returns an int value.

Napi::Number n = info[0].As<Napi::Number>();
 return Napi::Number::New(info.Env(), n);

actualclass.cpp file
// 
DAT ActualClass::openFile(int id)
{
  ifstream fin;
  filename += to_string(id) += ".txt";
  fin.open(filename.c_str(), ios_base::in | ios_base::binary);

  if (fin.is_open())
  {
    while (fin.read((char *)&data_s, sizeof(data_s)))
    {
      cout << setw(20) << data_s.name << ":"
           << setprecision(0) << setw(12) << data_s.width
           << setprecision(2) << setw(6) << data_s.height
           << setprecision(4) << setw(6) << data_s.size << endl;
      slist.push_back(data_s);
    }
    fin.close();

    cout << "List is are...";
    for (auto it = slist.begin(); it != slist.end(); ++it)
    {
      data_s = *it;
      cout << data_s.name << "\n";
    }
  }
  else if (!fin.is_open())
  {
    cout << "can't open file " << filename << ".\n";
    exit(EXIT_FAILURE);
  }
  return data_s;
}


// pure c++ class header file
#include <iostream>
#include <list>
#include <fstream>
#include <string>
#include <iterator>
#include <iomanip>

using namespace std;

const int LIM = 20;
typedef struct streamData
{
  int width;
  int height;
  int size;
  char name[LIM];
} DAT;

class ActualClass
{
  DAT data_s;
  char ch;
  list<DAT> slist;
   string filename;

public:
   ....

  DAT openFile(int id);
};


Thanks for Your time.
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900