一、
c/c++中调用python脚本,配置步骤,参见上一篇: http://www.cnblogs.com/SZxiaochun/p/5841242.html
main.cpp
#include <stdio.h>
#include "Python.h"
static PyObject* Py_Add_Formular(PyObject *self, PyObject *args)
{
PyObject *pObj = NULL;
int nThread = 0, nCalcData = -1, isDebug = 0, isCalcHis = 0;
if (!PyArg_ParseTuple(args, "Oiiii", &pObj, &nThread, &nCalcData, &isDebug, &isCalcHis)) //"Oiiii" O 代表 Object, i 代表 int
{
PyErr_Print();
return NULL;
}
return Py_True;
}
static PyMethodDef EmbMethods[]=
{
{"Add_Formular", Py_Add_Formular, METH_VARARGS, "Add formular."},
{NULL, NULL, 0, NULL}
};
int main()
{
Py_Initialize();
Py_InitModule("DJRJ", EmbMethods); //扩展 DJRJ 模块
PyObject *pModule = NULL;
PyObject *pFunc = NULL;
PyObject *pArg = NULL;
pModule = PyImport_ImportModule("Demo");
pFunc = PyObject_GetAttrString(pModule, "Start");
pArg = Py_BuildValue("(s)", "hello");
PyEval_CallObject(pFunc, pArg);
return 0;
}
Demo.py
#encoding=utf8
import DJRJ
class Test:
def __init__(self):
print "init"
def Start(self):
DJRJ.Add_Formular(self,1,500,0,1)
test = Test()
def Start(s):
print s
test.Start()
效果:
二、将模块生成lib、或直接安装到python库目录
DJRJ模块代码:
DJRJ.cpp
#include <stdio.h>
#include "Python.h"
static PyObject* Py_Add_Formular(PyObject *self, PyObject *args)
{
PyObject *pObj = NULL;
int nThread = 0, nCalcData = -1, isDebug = 0, isCalcHis = 0;
if (!PyArg_ParseTuple(args, "Oiiii", &pObj, &nThread, &nCalcData, &isDebug, &isCalcHis))
{
PyErr_Print();
return NULL;
}
printf("%d%d%d%d\r\n", nThread, nCalcData, isDebug, isCalcHis);
return Py_True;
}
/*
PyMethodDef结构体有四个字段。
第一个是字符串,表示在Python文件中对应的方法的名称;
第二个是对应的C代码的函数名称;
第三个是一个标志位,表示该Python方法是否需要参数,METH_NOARGS表示不需要参数,METH_VARARGS表示需要参数;
第四个是一个字符串,它是该方法的__doc__属性,这个不是必须的,可以为NULL。
PyMethodDef结构体数组最后以{NULL,NULL,0,NULL}结尾。
*/
static PyMethodDef DJRJMethods[]=
{
{"Add_Formular", Py_Add_Formular, METH_VARARGS, "Add formular."},
{NULL, NULL, 0, NULL}
};
/*
这个函数是用于模块初始化的,即是在第一次使用import语句导入模块时会执行。
其函数名必须为initmodule_name这样的格式,在这里我们的模块名为DJRJ,所以函数名就是initDJRJ。
在这个函数中又调用了PyInitModule函数,它执行了模块的初始化操作。
Py_InitModule函数传入了两个参数,第一个参数为字符串,表示模块的名称;第二个参数是一个Py_MethodDef的结构体数组,表示该模块都具有哪些方法。
因此在 initDJRJ 方法之前还需要先定义 DJRJMethods 数组。
*/
PyMODINIT_FUNC initDJRJ(void)
{
Py_InitModule("DJRJ", DJRJMethods);
}
创建一个setup.py 文件,编译最主要的工作由setup()函数来完成:
from setuptools import setup,Extension
MOD = 'DJRJ'
setup(name=MOD, ext_modules=[Extension(MOD, sources=['DJRJ.cpp'])])
执行命令进行编译:
python setup.py build
如果报错,得先安装setuptools,步骤如下:
1.下载ez_setup.py到某一个目录(如: e:\tools\ez_setup.py)下载地址: https://bootstrap.pypa.io/ez_setup.py
2.cmd进入e:\tools,运行python ez_setup.py
setuptools安装完毕之后:
再执行 python setup.py build
也可以执行 python setup.py install 直接安装到python库目录:
效果:
=
Demo程序:
百度云(13207134391):
CC++中调用Python\CExtenPythonModule