python内存地址与c++内存地址_C++中嵌入Python,从内存读入脚本

本文介绍了如何在C++程序中使用Python API创建模块,并定义函数。通过PyModule_New创建了一个名为'mymod'的模块,然后利用PyRun_String将Python代码动态执行,将结果保存在`pValue`中。接着,通过PyObject_GetAttrString获取函数对象,并用PyInt_FromLong构造参数,最后通过PyObject_CallObject调用函数并打印返回值。此示例展示了C++与Python之间的内存管理和交互能力。
摘要由CSDN通过智能技术生成

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):\n\tprint 5 * x\n\treturn 77\n", 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: %ld\n", PyInt_AsLong(pValue));

Py_DECREF(pValue);

Py_XDECREF(pFunc);

Py_DECREF(pNewMod);

Py_Finalize();

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值