本帖最后由 bailong360 于 2017-6-16 22:21 编辑
回复 11# misaki
测试过各系统下的兼容性吗? 感觉这个很有戏
试着编写了一个AddCmd tcc编译通过
将变量扩展和参数都处理了一下,应该是个通常情况下比较友好的接口- #include <stdio.h>
- #include <windows.h>
- #include <shellapi.h>
-
- #define DLL_EXPORT __declspec(dllexport)
- #define HANDLED 0
- #define UNHANDLED 1
- #define MAX_CMD_LENGTH 512
-
- typedef struct cmdTable {
- wchar_t cmd[MAX_CMD_LENGTH];
- int (*func)(int, wchar_t *[]);
- struct cmdTable *next;
- } CMDTABLE;
-
- DLL_EXPORT int ExtCallBack(wchar_t *, wchar_t *);
- char* WcharToChar(wchar_t *wstr);
- int AddCmd(int argc, wchar_t *cmdline[]);
-
- CMDTABLE cmd_Load = {L"AddCmd", AddCmd, NULL};
- CMDTABLE *head = &cmd_Load;
- CMDTABLE *tail = &cmd_Load;
-
- DLL_EXPORT int ExtCallBack(wchar_t *cmd, wchar_t *cmdline)
- {
- CMDTABLE *current = head;
- do {
- if (!wcsnicmp(cmd, current->cmd, wcslen(current->cmd))) {
- int argc;
- wchar_t **argv;
- wchar_t newcmdline[MAX_CMD_LENGTH];
- ExpandEnvironmentStringsW(cmdline, newcmdline, MAX_CMD_LENGTH + 1);
- newcmdline[wcslen(newcmdline) - 2] = '\0'; //去除末尾的\n
- argv = CommandLineToArgvW(newcmdline, &argc);
- current->func(argc, argv);
- LocalFree(argv);
- return HANDLED;
- }
- current = current -> next;
- } while (current != NULL);
- return UNHANDLED;
- }
-
- char* WcharToChar(wchar_t *wstr)
- {
- int len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);
- char *str = (char *)malloc(len * sizeof(char));
- WideCharToMultiByte(CP_ACP, 0, wstr, -1, str, len, NULL, NULL);
- return str;
- }
-
- int AddCmd(int argc, wchar_t *argv[])
- {
- if (argc < 4) {
- puts("Usage: AddCmd YourCmd YourDll YourFunc");
- puts("**YourFunc should be defined like this \"int YourFunc(int argc, wchar_t *argv[])\"");
- return 0;
- }
- HMODULE hDLL = LoadLibraryW(argv[2]);
- char *funcName = WcharToChar(argv[3]);
- void *func = (void *)GetProcAddress(hDLL, funcName);
-
- if (hDLL == NULL) {
- fprintf(stderr, "ERROR:can't load dll \"%S\"", argv[2]);
- free(funcName);
- return 0;
- } else if (func == NULL) {
- fprintf(stderr, "ERROR:can't load func \"%s\"", funcName);
- free(funcName);
- return 0;
- }
- tail->next = (CMDTABLE *)malloc(sizeof(CMDTABLE));
- wcscpy(tail->next->cmd, argv[1]);
- tail->next->func = (void *)GetProcAddress(hDLL, funcName);
- tail->next->next = NULL;
- tail = tail->next;
- free(funcName);
- return 0;
- }
复制代码
|