It is actually a lot easier than this. You just need the mame binary from the retrocade build, and not the whole directory. Just rename the file called “mame” in /opt/retropie/emulators/mame4all-pi/ to something else …
mv /opt/retropie/emulators/mame4all-pi/mame /opt/retropie/emulators/mame4all-pi/mame.orig
Then copy the “mame” file from retrocade to that same directory. Next time you start the MAME emulator you might have to remap a few buttons by pressing “tab” to get to the options menu, but you should be able to use up to 22 buttons instead of 16.

Keep in mind if you upgrade RetroPie it might overwrite the mame binary so you would have to repeat this process.

To make it easier, I have included a link to the fixed “mame” file on Google Drive. You can access it here.