In case someone is interested, I was finally able to get the keyboard layout with the following code:
#include <Carbon/Carbon.h>
int main() {
char layout[128];
memset(layout, '\0', sizeof(layout));
TISInputSourceRef source = TISCopyCurrentKeyboardInputSource();
// get input source id - kTISPropertyInputSourceID
// get layout name - kTISPropertyLocalizedName
CFStringRef layoutID = TISGetInputSourceProperty(source, kTISPropertyInputSourceID);
CFStringGetCString(layoutID, layout, sizeof(layout), kCFStringEncodingUTF8);
printf("%s\n", layout);
return 0;
}
Compiled with:
gcc -o test2 test2.c -framework Carbon