环境:Win10 + VS2017 + Anaconda3 + Python3.6
注意:在Debug模式有可能编译错误,换成release就好。
1.添加python3.6中对应的include和libs
复制一份libs下的python36.lib,并重命名为python36_d.lib,添加到连接器输出
配置完成,测试(来源:https://blog.csdn.net/qq_31342997/article/details/88368420):
#include<iostream>
#include<algorithm>
#include<queue>
#include<cmath>
#include<string>
#include<map>
#include<unordered_map>
#include<set>
#include<unordered_set>
#include<vector>
#include<iomanip>
#include<queue>
#include<stack>
#include<Python.h>
#include<stdio.h>
#include<direct.h>
using namespace std;
int main()
{
long CArray[2][3] = { {2,3,4},{5,6,7} };
Py_Initialize();
PyObject * pModule = NULL;
PyObject * pFunc = NULL;
PyObject *pDict = NULL;
PyObject *pReturn = NULL;
pModule = PyImport_ImportModule("demo_test");
pDict = PyModule_GetDict(pModule);
pFunc = PyDict_GetItemString(pDict, "szSecTest");
cout << "C two-dim Array Pass Into The Python List:" << endl;
PyObject *PyList = PyList_New(0);//定义该PyList对象为0和PyList_Append有关,相当于定义PyList为[]
PyObject *ArgList = PyTuple_New(1);
for (int i = 0; i < 2; i++) {
PyObject *PyList1 = PyList_New(3);
for (int j = 0; j < 3; j++) {
PyList_SetItem(PyList1, j, PyLong_FromLong(CArray[i][j]));
}
PyList_Append(PyList, PyList1);//PyList_Append可以参考Python中,list的append的用处
}
PyTuple_SetItem(ArgList, 0, PyList);//将PyList对象放入PyTuple对象中
pReturn = PyObject_CallObject(pFunc, ArgList);//调用函数,返回一个list
if (PyList_Check(pReturn)) { //检查是否为List对象
//cout << "enter" << endl;
int SizeOfList = PyList_Size(pReturn);//List对象的大小,这里SizeOfList = 2
printf("返回的结果result:\n");
for (int i = 0; i < SizeOfList; i++) {
PyObject *ListItem = PyList_GetItem(pReturn, i);//获取List对象中的每一个元素
int NumOfItems = PyList_Size(ListItem);//List对象子元素的大小,这里NumOfItems = 3
for (int j = 0; j < NumOfItems; j++) {
PyObject *Item = PyList_GetItem(ListItem, j);//遍历List对象中子元素中的每个元素
int result;
PyArg_Parse(Item, "i", &result);//i表示转换成int型变量
printf("%d ", result);
//cout << PyInt_AsLong(Item) <<" "; //输出元素
Py_DECREF(Item); //释放空间
}
cout << endl;
Py_DECREF(ListItem); //释放空间
}
}
return 0;
}
demo_test.py(注意和exe放在同一目录)
#coding:utf-8
import os
def szSecTest(List):
print (List)
IntegerList = [[1, 2, 3],[2,3,4]]
return IntegerList