X Tutup
The Wayback Machine - https://web.archive.org/web/20220405131729/https://github.com/nodejs/node-addon-api/issues/813
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to return objects in class methods? #813

Closed
kaysonwu opened this issue Sep 12, 2020 · 3 comments
Closed

How to return objects in class methods? #813

kaysonwu opened this issue Sep 12, 2020 · 3 comments

Comments

@kaysonwu
Copy link

@kaysonwu kaysonwu commented Sep 12, 2020

I have the following 2 classes, now I need to encapsulate Hero into a node module

class Pet {
    public:
        Pet(const char* name);
        void Say();
    protected:
        const char* Name;
}

class Hero {
    public:
        Hero(const char* name);
        Pet GetPet();
    protected:
         const char* Name;
        Pet Pet;
}

I refer to the Wrapping C++ Object example, but I cannot complete the encapsulation of the GetPet method in the Hero class.

How can I implement GetPet to return the Pet object and customize its public methods?

@kaysonwu
Copy link
Author

@kaysonwu kaysonwu commented Sep 12, 2020

I made an example 9_object_wrap, I found that the Pet object was free early, how can I solve it?

@mhdawson
Copy link
Member

@mhdawson mhdawson commented Sep 22, 2020

@kaysonwu I think the problem is this line Pet(Pet::New(info.Env(), info[1].As<Napi::String>()))

This results in a a Pet JavaScript object that will only live as long as the method Hero::Hero is running since the object is not returned by the method and no JavaScript object references the object in the JavaScript heap. You do have a reference at the C++ level but that will not keep the object alive.

I think you need to use an ObjectReference https://github.com/nodejs/node-addon-api/blob/master/doc/object_reference.md. When hero is then destructed that should then result in the reference count to Pet being decreased and it being ready to be collected by the garbage collector.

@gabrielschulhof
Copy link
Contributor

@gabrielschulhof gabrielschulhof commented Dec 4, 2020

@kaysonwu hopefully @mhdawson's suggestion solved the problem you were experiencing. Please re-open the issue if you believe there is any functionality in node-addon-api that needs to change to better support your use case!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants
X Tutup