Python 2.7.13,VS2015
VS环境配置:
1. Release 环境配置:
包含目录:
D:\Miniconda2\include
附加依赖项:
D:\Miniconda2\libs\python27.lib
并且确定python27.dll的路径在环境变量中。
2.Debug 环境配置
修改附加依赖项为:
D:\Miniconda2\libs\python27_d.lib
并且确定python27_d.dll的路径在环境变量中。
我使用的是miniconda管理python,所以上面的配置路径是这样的。因为安装的 python自由release版本的静态库和动态库,因此需要手动编译python源代码,生成自己需要版本的debug版本的lib和dll。
1. C/C++ 调用python
main.c
#include "stdafx.h"
#include <Python.h>
#include<iostream>
using namespace std;
int func_copy_from_python(int a)
{
int res;
PyObject * module, *func;
PyObject *args, *value;
// 导入module
module = PyImport_Import(PyString_FromString("modulename"));
// 获取module中的函数
func = PyObject_GetAttrString(module, "power_func");
// 建立参数
args = PyTuple_New(1);
PyTuple_SetItem(args, 0, PyInt_FromLong(a));
// 调用python module中的函数
value = PyObject_CallObject(func, args);
// 转换为C类型数据
res = PyInt_AsLong(value);
return res;
}
int main(int argc, char ** argv)
{
Py_SetProgramName(argv[0]);
Py_Initialize();
// do something
int a = 10;
cout << "result: " << func_copy_from_python(a) << endl;
//PyRun_SimpleString("print 'Hello Python!'\n");
Py_Finalize();
return 0;
}
modulename.py
#-*-coding:utf-8-*-
'''
Created on 2017年4月27日
@author: Administrator
'''
def power_func(a):
return a*a
#print power_func(10)
2.Python 调用C/C++
#include<iostream>
#include<Python.h>
using namespace std;
//函数的具体实现,由C/C++完成
int power_func(int a)
{
return a*a;
}
/*
包裹函数:_power_func,它负责将Python参数转换为C参数(利用PyArg_ParseTuple),
通过调用函数 power_func 完成具体的任务,并将返回值,转化后返回给Python环境
*/
static PyObject * _power_func(PyObject *self, PyObject *args)
{
int _a; // 中间变量
int res;
if (!PyArg_ParseTuple(args, "i", &_a))//将python参数转换为C参数
return NULL;
res = power_func(_a);
return PyLong_FromLong(res);
}
/*
导出表:moduleMethod. 它负责告诉Python这个模块中,有哪些函数可以被Python调用。
导出表的名字可以随便起,每一项有4个参数:
第一个参数是提供给Python环境的函数名字。
第二个参数_power_func,即包裹函数。
第三个参数的含义是参数变长。
第四个参数是一个说明性的字符串。
导出表总是以{NULL,NULL,0,NULL}结束。
*/
static PyMethodDef moduleMethod[] = {
{
"power_func",
_power_func,
METH_VARARGS,
""
},
{NULL,NULL,0,NULL}
};
/*
导出函数:initmodulename ,这个的名字不是任意取,是你的module名称添加前缀init。
导出函数中,将模块名称与导出表进行连接。
*/
PyMODINIT_FUNC initmymodule(void)
{
(void)Py_InitModule("mymodule", moduleMethod);
}