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[] = "\"byExposureModeSet\" : \"2\", \"byFocusMode\" : \"2\", \"wMinFocusDistance\" : \"10\"";
printf("%s\n", str); Json stuJson = {};
memset(&stuJson, , sizeof(stuJson)); HandleStr(str, &stuJson); printf("stuJson.byExposureModeSet = %d, stuJson.byFocusMode = %d, stuJson.wMinFocusDistance = %d\n",
stuJson.byExposureModeSet, stuJson.byFocusMode, stuJson.wMinFocusDistance); return ;
} int HandleStr(char *pStr, Json *pStuJson)
{
int iRet = -;
char *tmp = pStr; char key[] = {};
char value[] = {}; while(tmp != NULL)
{ memset(key, , sizeof(key));
memset(value, , sizeof(value));
iRet = GetValue(&tmp, key);
tmp = strstr(tmp, ":") + ; iRet = GetValue(&tmp, value); printf("{%s} : {%s}\n", key, value);
if ( == strcmp(key, "byExposureModeSet"))
{
pStuJson->byExposureModeSet = atoi(value);
}
else if ( == strcmp(key, "byFocusMode"))
{
pStuJson->byFocusMode = atoi(value);
}
else if ( == strcmp(key, "wMinFocusDistance"))
{
pStuJson->wMinFocusDistance = atoi(value);
}
tmp = strstr(tmp, ",");
}
return iRet;
} int GetValue(char **pStr, char *pValue)
{
int iRet = ; char *pBegin = *pStr;
char *pEnd = NULL; pBegin = strstr(pBegin, "\"");
pEnd = strstr(pBegin+, "\""); int len_str = pEnd-pBegin;
memcpy(pValue, pBegin+, len_str-);
//printf("pValue = {%s}\n", pValue); iRet = len_str; *pStr = pEnd;
return iRet;
} int DelLeftSpace(char *szbuf)
{
int iRet = -;
int iLen = ;
int i = ;
int j = ;
int k = ; if(NULL != szbuf)
{
iRet = ;
iLen = strlen(szbuf);
for(i = ; i < iLen; i++)
{
if( (' ' != szbuf[i]) && ('\t' != szbuf[i])
&& ('\r' != szbuf[i]) && ('\n' != szbuf[i]) )
{
if( != i)
{
j = i;
k = ;
while(j < iLen)
{
szbuf[k++] = szbuf[j++];
}
szbuf[k] = '\0';
}
break;
} if (i == (iLen - ))
{
szbuf[] = '\0';
break;
}
}
} return iRet;
} int DelRightSpace(char *szbuf)
{
int iRet = -;
int iLen = ;
int i = ; if(NULL != szbuf)
{
iRet = ;
iLen = strlen(szbuf);
for(i = (iLen - ); i >= ; i--)
{
if( (' ' != szbuf[i]) && ('\t' != szbuf[i])
&& ('\r' != szbuf[i]) && ('\n' != szbuf[i]) )
{
if(i != iLen - )
{
szbuf[i+] = '\0';
}
break;
} if(i <= )
{
szbuf[] = '\0';
break;
}
}
} return iRet;
} void EarseSpace(char *pStr)
{
char *pTmp = pStr;
int len = strlen(pTmp);
int i = len - ;
for (; i > ; i--)
{
if (pTmp[i-] != ' ')
{
pTmp[i] = ;
break;
}
} int k = ;
int j = ;
for (i = ; i < len; i++)
{
if (i != && pTmp[i] != ' ')
{
k = i;
while(k < len)
{
pTmp[j++] = pTmp[k++];
}
break;
}
} pStr = pTmp;
}