Is there a way to call an initialiser when a module is loaded?

C programming, build, interpreter/VM.
Target audience: MicroPython Developers.
Post Reply
mianos
Posts: 84
Joined: Sat Aug 22, 2015 6:42 am

Is there a way to call an initialiser when a module is loaded?

Post by mianos » Sat Aug 22, 2015 6:50 am

I have a C module (spin free DHT22 module for the ESP8266, unlike all the existing 'interrupt' based ones that busy loop, wtf) and an interrupt framework.

I am working on making it work for multiple concurrent and I want to initialise the interrupt handler table when the module is loaded.
I know I can simply call a function after I load the module, but is there an example in one of the modules or a suggested way to do this?
- Rob from Sydney

User avatar
dhylands
Posts: 3821
Joined: Mon Jan 06, 2014 6:08 pm
Location: Peachland, BC, Canada
Contact:

Re: Is there a way to call an initialiser when a module is loaded?

Post by dhylands » Sat Aug 22, 2015 5:05 pm

The stuff done in C is defining classes (or types). There isn't really a notion of loading a module from the C side of things.

When you load a python module, then all of the code in the module is executed, so if you made your module be a python file which was loaded, the python can reference the C types and call a function.

For the other peripherals, what happens now is that a call to an init function happens from main, for example, this call to dac_init:
https://github.com/micropython/micropyt ... ain.c#L565

There are 3 different places that we call init from C, in roughly these categories:
1 - Before the heap is initialized
2 - After the heap is initialized and before boot.py/USB. These functions are xxx_init0()
3 - After USB is initialized (also after boot.py is run). These functions are xxx_init()

Curently, we need to edit main.c and stick init calls in the right places. I'd like to propose that we do something like the linux kernel's initcall mechanism. I opened up an issue in github: https://github.com/micropython/micropython/issues/1436 to discuss this.

For now, you either need to put a call in main.c or do your initialization the first time an instance of your class is created.

Post Reply