2

DriverKit provides IONewZero and IOSafeDeleteNULL. Those does not call any constructor or destructor.

Let's say that I would like to have some class in the ivars structure. The class does not need to inherit from OSObject nor IOService. How should I construct this object? If I have it as a member in the ivars struct the constructor of my class is not called. If I keep a pointer to my class in the ivars structure I need to allocate and call the constructor of the class. Can I use new / delete for this?

pmdj
  • 22,018
  • 3
  • 52
  • 103
tuple_cat
  • 1,165
  • 2
  • 7
  • 22
  • "_There are no alignment guarantees on the returned memory_" looks scary. Perhaps [`OSTypeAlloc`](https://developer.apple.com/documentation/driverkit/ostypealloc?language=objc) is a better choice? – Ted Lyngmo Jun 16 '20 at 12:51

1 Answers1

1

The default operator new is indeed implemented in the DriverKit runtime. I've used it successfully to allocate and initialise my …_IVars objects themselves. (the PIMPL type that's automatically forward-declared by the header generated by iig for any classes defined in .iig files)

So, I actually do this in MyDriver::init():

    this->ivars = new MyDriver_IVars();

and then in MyDriver::free():

    if (this->ivars != nullptr)
    {
        // … some extra cleanup …

        delete this->ivars;
        this->ivars = nullptr;
    }

In my opinion this is about the cleanest approach achievable given the constraints forced upon us by the iig system.

I strongly suspect operator new is implemented with the same back-end as in regular macOS user space, though I've not actually gone and checked yet as I've not encountered any issues with it at all so far. Obviously, the corresponding delete works too.

OSTypeAlloc is for OSObject-derived types and should definitely be used for those, but won't work for other types.

pmdj
  • 22,018
  • 3
  • 52
  • 103
  • 1
    Evidence I found, Apple doesn't want us to use new even though it is usable. I would strongly disagree using new/delete. Instead have a look in the available choices - [LINK](https://developer.apple.com/documentation/driverkit/memory_utilities) – skratchi.at Apr 06 '21 at 06:03