一:环境VS2015,Python3.7,Windows 64位操作系统
二:环境配置自行百度
三:新建VS控制台工程,并在工程目录下创建PyModule.py文件
四:编写PyModule.py文件,代码如下:
def retNum():
return 12345
def retDouble():
return 12345.6789
def retString():
return "Hello,World!"
def retUString():
return "你好,中国!".encode("gb18030")
def retList():
return [1,2,3,4,5]
def retTuple():
return (1,2,"Hello,World!")
def retDict():
d = dict()
d[1] = "C"
d[2] = "C++"
d[3] = "Python"
return d
五:编写C++文件,调用Python模块。
// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <python.h>
#include <iostream>
using namespace std;
int main()
{
string chdir_cmd = string("sys.path.append(\"") + "\")"; //Python模块在当前目录下
const char* cstr_cmd = chdir_cmd.c_str();
PyObject* pRet;
PyObject* pModule;
PyObject *pFunc;
Py_Initialize(); //初始化Python环境
PyRun_SimpleString("import sys"); //运行Python语句
PyRun_SimpleString(cstr_cmd); //添加Python模块路径
pModule = PyImport_ImportModule("PyModule");
if (!pModule)
{
cout << "Can't Find The Module,Please Check Module Name and try again!" << endl;
return 0;
}
pFunc = PyObject_GetAttrString(pModule, "retNum"); //调用retNum函数,返回整型
if (pFunc && PyCallable_Check(pFunc))
{//为使代码紧凑,仅写第一次,后面同上处理,忽略判断
pRet = PyObject_CallObject(pFunc, NULL);
cout << PyLong_AsLong(pRet) << endl;
}
pFunc = PyObject_GetAttrString(pModule, "retDouble"); //调用retDouble,返回double类型
pRet = PyObject_CallObject(pFunc, NULL);
cout << PyFloat_AsDouble(pRet) << endl;
pFunc = PyObject_GetAttrString(pModule, "retString"); //调用retString,返回ANSI字符串
pRet = PyObject_CallObject(pFunc, NULL);
cout << PyUnicode_AsUTF8(pRet) << endl;
pFunc = PyObject_GetAttrString(pModule, "retUString"); //调用retUString,返回Unicode字符串
pRet = PyObject_CallObject(pFunc, NULL);
cout << PyBytes_AsString(pRet) << endl;
pFunc = PyObject_GetAttrString(pModule, "retList"); //调用retList,返回数组类型。
pRet = PyObject_CallObject(pFunc, NULL);
_int64 val_num = PyList_Size(pRet);
for (int i = 0; i < val_num; i++)
{
cout << PyLong_AsLong(PyList_GetItem(pRet, i)) << " ";
}
cout << endl;
pFunc = PyObject_GetAttrString(pModule, "retTuple"); //调用retTuple,返回tuple类型
int w = 0, h = 0;
char *ret_str;
pRet = PyObject_CallObject(pFunc, NULL);
PyArg_ParseTuple(pRet, "iis", &w, &h, &ret_str); //多个值必须一一对应
cout << w << " " << h << " " << ret_str << endl;
pFunc = PyObject_GetAttrString(pModule, "retDict"); //调用retDict,返回dict类型
pRet = PyObject_CallObject(pFunc, NULL);
PyObject* pKeys = PyDict_Keys(pRet);
PyObject* pValues = pRet;
_int64 LongList = PyDict_Size(pRet);
for (int i = 0; i < LongList; i++)
{
PyObject *pKey = PyList_GetItem(pKeys, i);
PyObject *pValue = PyDict_GetItem(pValues, pKey);
cout << PyLong_AsLong(pKey) << ":" << PyUnicode_AsUTF8(pValue) << endl;
}
Py_Finalize();
system("pause");
return 0;
}