c语言调用python3_linux下c语言调用python方法问题
//c語言多線程調python,必須加上紅色字體,因為python本身不是線程安全的
PyObject* callPython(char* cpModelPath)
{
if(cpModelPath == NULL)
return NULL;
char modelPath[100] = "";
char modelName[21] = "";
int i;
char* cp = cpModelPath;
int len = strlen(cp);
int len1 = len;
if(len <= 0)
{
printf( "model is null, pid [%u] exit\n", (unsigned int)getpid() );
return;
}
while( *(cp + len - 1) != '/')
{
len--;
}
for(i = 0; i < len; ++i)
modelPath[i] = *(cp+i);
for(i = 0; i < len1-len; ++i)
modelName[i] = *(cp+i+len);
char modelPath1[100] = "";
strcpy(modelPath1, "sys.path.append('");
strcat(modelPath1, modelPath);
strcat(modelPath1, "')");
PyRun_SimpleString("import sys");
PyRun_SimpleString(modelPath1);
PyObject* pModule = NULL;
PyObject* pDict = NULL;
PyObject* pClass = NULL;
PyObject* pObject = NULL;
PyObject* pFunc = NULL;
//調用python中的類
pModule = PyImport_ImportModule(modelName);
if(!pModule)
{
printf( "model PyImport_ImportModule fail, pid [%u] thread [%u] exit\n",
(unsigned int)getpid(), (unsigned int)pthread_self() );
return;
}
pDict = PyModule_GetDict(pModule);
if(!pDict)
{
printf( "model PyModule_GetDict fail, pid [%u] thread [%u] exit\n",
(unsigned int)getpid(), (unsigned int)pthread_self() );
return;
}
pClass = PyObject_GetAttrString(pModule, "JobNode");//得到那個類
if(!pClass || !PyCallable_Check(pClass))
{
printf( "model PyObject_GetAttrString class fail, pid [%u] thread [%u] exit\n",
(unsigned int)getpid(), (unsigned int)pthread_self() );
return;
}
pObject = PyEval_CallObject(pClass, NULL);//生成一個對象,或者叫作實例
pFunc= PyObject_GetAttrString(pObject, "createApp");//得到該實例的成員函數
if(!pFunc || !PyCallable_Check(pFunc))
{
printf( "model PyObject_GetAttrString func fail, pid [%u] thread [%u] exit\n",
(unsigned int)getpid(), (unsigned int)pthread_self() );
return;
}
Py_DECREF(pObject);
Py_DECREF(pClass);
Py_DECREF(pDict);
Py_DECREF(pModule);
return pFunc;
}
void* func(void* arg)
{
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
PyObject* pFunc = NULL;
PyObject* pArg = NULL;
PyObject* pString = NULL;
char* cpReturn;
PyObject* p = callPython("/mnt/hgfs/D/emar_test/linux-test/marmoset/JobNode");
pFunc = p;
pArg = PyTuple_New(1);
// s 表示字符串,
// i 表示整型變量,
// f 表示浮點數,
// O 表示一個Python對象。
PyTuple_SetItem(pArg, 0, Py_BuildValue("s", "Jacky"));
pString = PyEval_CallObject(pFunc, pArg);//執行該實例的成員函數
cpReturn = PyString_AsString(pString);
printf("cpReturn=%s\n",cpReturn);
Py_DECREF(pString);
Py_DECREF(pArg);
Py_DECREF(pFunc);
PyGILState_Release(gstate);
}
void main()
{
int num = 1;
Py_Initialize();
if(!Py_IsInitialized())
{
return;
}
PyEval_InitThreads();
PyEval_ReleaseThread(PyThreadState_Get());
pthread_t pid1,pid2;
pthread_create(&pid1, NULL, func, NULL);
pthread_create(&pid2, NULL, func, NULL);
pthread_join(pid1, NULL);
pthread_join(pid2, NULL);
PyGILState_Ensure();
Py_Finalize();*/
}
總結
以上是生活随笔為你收集整理的c语言调用python3_linux下c语言调用python方法问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: page 怎么把list 分页_自定义分
- 下一篇: linux 文件 跳板机_shell实现