python调用C库时参数太多,约定传json格式字符串,C解析
#include<stdio.h> #include<string.h> #include<stdlib.h> typedef struct __Json_ { int byExposureModeSet; int byFocusMode; int wMinFocusDistance; }Json; int HandleStr(char *pStr, Json *pStuJson); int GetValue(char **pStr, char *pValue); void EarseSpace(char *pStr); int DelLeftSpace(char *szbuf); int DelRightSpace(char *szbuf); int main() { char str[1024] = "\"byExposureModeSet\" : \"2\", \"byFocusMode\" : \"2\", \"wMinFocusDistance\" : \"10\""; printf("%s\n", str); Json stuJson = {0}; memset(&stuJson, 0, sizeof(stuJson)); HandleStr(str, &stuJson); printf("stuJson.byExposureModeSet = %d, stuJson.byFocusMode = %d, stuJson.wMinFocusDistance = %d\n", stuJson.byExposureModeSet, stuJson.byFocusMode, stuJson.wMinFocusDistance); return 0; } int HandleStr(char *pStr, Json *pStuJson) { int iRet = -1; char *tmp = pStr; char key[64] = {0}; char value[64] = {0}; while(tmp != NULL) { memset(key, 0, sizeof(key)); memset(value, 0, sizeof(value)); iRet = GetValue(&tmp, key); tmp = strstr(tmp, ":") + 1; iRet = GetValue(&tmp, value); printf("{%s} : {%s}\n", key, value); if (0 == strcmp(key, "byExposureModeSet")) { pStuJson->byExposureModeSet = atoi(value); } else if (0 == strcmp(key, "byFocusMode")) { pStuJson->byFocusMode = atoi(value); } else if (0 == strcmp(key, "wMinFocusDistance")) { pStuJson->wMinFocusDistance = atoi(value); } tmp = strstr(tmp, ","); } return iRet; } int GetValue(char **pStr, char *pValue) { int iRet = 0; char *pBegin = *pStr; char *pEnd = NULL; pBegin = strstr(pBegin, "\""); pEnd = strstr(pBegin+1, "\""); int len_str = pEnd-pBegin; memcpy(pValue, pBegin+1, len_str-1); //printf("pValue = {%s}\n", pValue); iRet = len_str; *pStr = pEnd; return iRet; } int DelLeftSpace(char *szbuf) { int iRet = -1; int iLen = 0; int i = 0; int j = 0; int k = 0; if(NULL != szbuf) { iRet = 0; iLen = strlen(szbuf); for(i = 0; i < iLen; i++) { if( (' ' != szbuf[i]) && ('\t' != szbuf[i]) && ('\r' != szbuf[i]) && ('\n' != szbuf[i]) ) { if(0 != i) { j = i; k = 0; while(j < iLen) { szbuf[k++] = szbuf[j++]; } szbuf[k] = '\0'; } break; } if (i == (iLen - 1)) { szbuf[0] = '\0'; break; } } } return iRet; } int DelRightSpace(char *szbuf) { int iRet = -1; int iLen = 0; int i = 0; if(NULL != szbuf) { iRet = 0; iLen = strlen(szbuf); for(i = (iLen - 1); i >= 0; i--) { if( (' ' != szbuf[i]) && ('\t' != szbuf[i]) && ('\r' != szbuf[i]) && ('\n' != szbuf[i]) ) { if(i != iLen - 1) { szbuf[i+1] = '\0'; } break; } if(i <= 0) { szbuf[0] = '\0'; break; } } } return iRet; } void EarseSpace(char *pStr) { char *pTmp = pStr; int len = strlen(pTmp); int i = len - 1; for (; i > 0; i--) { if (pTmp[i-1] != ' ') { pTmp[i] = 0; break; } } int k = 0; int j = 0; for (i = 0; i < len; i++) { if (i != 0 && pTmp[i] != ' ') { k = i; while(k < len) { pTmp[j++] = pTmp[k++]; } break; } } pStr = pTmp; }