C++ module New/Delete and math and C libraries

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
jgpeiro
Posts: 7
Joined: Wed Aug 05, 2015 8:27 am

C++ module New/Delete and math and C libraries

Post by jgpeiro » Tue May 24, 2022 6:35 pm

I have a C++ code that I can compile as Cpp module following the upy 1.18 documentation, but Im not sure how to "link" New and Delete operators with micropython garbage collector.

Im wondering if this is the correct way:

Code: Select all

void *operator new(size_t size) {
    return gc_alloc(size, 0);
}

void *operator new[](size_t size) {
  return gc_alloc(size, 0);
}

void operator delete(void *p) {
    gc_free(p);
}

void operator delete[](void *p) {
    gc_free(p);
}
Also my C++ code is a precompiled library that depends on math library, but I have some problems cause G++ cant link with the sin/cos functions offered by micropython.


My micropython.mk is:

Code: Select all

CPPEXAMPLE_MOD_DIR := $(USERMOD_DIR)

# Add our source files to the respective variables.
SRC_USERMOD += $(CPPEXAMPLE_MOD_DIR)/ppl_module.c << here are the mp_rom_map_elem_t ppl_module_globals_table
SRC_USERMOD += $(CPPEXAMPLE_MOD_DIR)/sysmem.c  << here I needed to reimplement syscall _sbrk. I think I can solve with new/delete overloading and redirecting to upy gc.
SRC_USERMOD += $(CPPEXAMPLE_MOD_DIR)/syscalls.c << here I reimplemented mocks of _read, _write, _lseek...needed by -lc
SRC_USERMOD_CXX += $(CPPEXAMPLE_MOD_DIR)/ppl.cpp << here are the upy<>cpp wrappers

# Add our module directory to the include path.
CFLAGS_USERMOD += -I$(CPPEXAMPLE_MOD_DIR)
CXXFLAGS_USERMOD += -I$(CPPEXAMPLE_MOD_DIR) -std=c++11

LDFLAGS_USERMOD += -lpointperfect - lstdc++ -lc -lm -L$(USERMOD_DIR)
I think -lm is duplicated cause micropython uses its own implementation, and I think -lc too.

Can someone with more experience guide me?

stijn
Posts: 735
Joined: Thu Apr 24, 2014 9:13 am

Re: C++ module New/Delete and math and C libraries

Post by stijn » Mon May 30, 2022 6:42 am

I think what you're doing would work. Only way to make sure is write tests and/or run your application enough times. First question though is whether it is needed: if the object created by new isn't actually going to be used by MicroPython itself, you can just allocate it from the normal C++ heap (which would potentially be faster). And if it is needed e.g. to wrap it in a mp_obj_t then you could still allocate it from the C++ heap and something like shown here also works: https://github.com/micropython/micropython/issues/8691.

Wrt linking: can you provide a minimal sample to reproduce the problem?

Post Reply