C++ 调用python文件

环境: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

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值