C++中嵌入Python,从内存读入脚本

发布时间:2019-08-06 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了C++中嵌入Python,从内存读入脚本脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
int main()
{
    PyObject *pName, *pModule, *pargs, *pvalue, *pFunc;
    PyObject *pGlobal = PyDict_New();
    PyObject *pLocal;

    //Create a new module object
    PyObject *pNewMod = PyModule_New("mymod");

    Py_InITialize();
    PyModule_AddStringConstant(pNewMod, "__FILE__", "");

    //Get the dictionary object From my module so I can pass this to PyRun_String
    pLocal = PyModule_GetDict(pNewMod);

    //define my function in the newly created module
    pValue = PyRun_String("def blah(x):ntPRint 5 * xntreturn 77n", Py_file_input, pGlobal, pLocal);
    Py_DECREF(pValue);

    //Get a pointer to the function I just defined
    pFunc = PyObject_GetAttrString(pNewMod, "blah");

    //Build a tuple to hold my arguments (just the number 4 in this case)
    pArgs = PyTuple_New(1);
    pValue = PyInt_FromLong(4);
    PyTuple_SetItem(pArgs, 0, pValue);

    //Call my function, passing it the number four
    pValue = PyObject_CallObject(pFunc, pArgs);
    Py_DECREF(pArgs);
    printf("Returned val: %ldn", PyInt_AsLong(pValue));
    Py_DECREF(pValue);

    Py_XDECREF(pFunc);
    Py_DECREF(pNewMod);
    Py_Finalize();

    return 0;
}

参考:
http://stackoverflow.com/questions/3789881/create-and-call-python-function-from-string-via-c-api?s=737aab37-4e1e-4945-a887-16dd97cfece1#new-answer

脚本宝典总结

以上是脚本宝典为你收集整理的C++中嵌入Python,从内存读入脚本全部内容,希望文章能够帮你解决C++中嵌入Python,从内存读入脚本所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。