C++调用python得到数据

前面一篇文章介绍了C++调用python的两种方法。

  • PyRun_SimpleString方法简单,数据传递不方便,但是可以保存数据到txt中
  • PyObject_GetAttrString方法繁琐,可以传递数据,但是有时候会PyObject_CallObject返回NULL错误,查了差不多3个小时,尝试了无数种方法还是找不到原因,同时我主要学习语言为python,因此打算该放弃。
  • 综上,我打算采用PyRun_SimpleString方法进行C++调用python。对于数据传递问题是将放回的数据写入txt文件进行读取。

首先对于python

在python编写一个函数,将需要结果存入文件中,文件名与路径需要固定,最好是在当前目录之下

import numpy as np
def hello(x='12',y='1'):
    if not isinstance(x, str):
        x="helloxx! {}".format(x)
    else:
        x=("helloxx!"+x)
    writeToTxt(x)
    return x
 
def add(a, b):
    return a+b


def writeToTxt(data=data):
    if not isinstance(data, str):
        data=str(data)
    with open('data.txt','w') as f:
        f.write(data)




if __name__ == '__main__':
    xx = np.array([1, 23, 4156])
    print(xx)
    data=hello('52889898')
    writeToTxt()
    print(data)

对于txt文本

在这里插入图片描述

对于VS2017 的c++

在文件读写过程中使用多种字符串进行尝试,如char* ,string,CString,发现char*返回之后出现乱码,也不知道怎么解决,抛弃。
在这里插入图片描述
之后使用string
在这里插入图片描述
使用CString
在这里插入图片描述
因为感觉string不用添加#include <atlstr.h>和改变字符集,因此采用string
在这里插入图片描述

#include <Python.h>
#include<iostream>
#include<fstream>
//#include <atlstr.h>
#include <string> 
using namespace std;


string openFile()
{
	// *************************读txt文件*******************************
	string data;
	ifstream infile;
	infile.open("data.txt");
	infile >> data;
	return data;

	//ifstream infile2("data.txt");
	//CString m_phone;
	//char* charpoint = new char[360];
	//int count = 0;
	//while (!infile2.eof())
	//{
	//	charpoint[count] = infile2.get();
	//	count++;
	//}
	//charpoint[count] = '\0';
	//m_phone = charpoint;//将number.txt中的字符串转换为CString类。
	//return m_phone;

}

int main()
{
	Py_SetPythonHome(L"D:/anaconda3");//这里地址一定要写对啊!
	/**	添加python.exe所在路径,不添加在运行时出现
	Fatal Python error: initfsencoding: unable to load the file system codec
	ModuleNotFoundError: No module named 'encodings'**/
	Py_Initialize();//使用python之前,要调用Py_Initialize();这个函数进行初始化
	if (!Py_IsInitialized())
	{
		printf("初始化失败!");
		return 0;
	}
	else {
		PyRun_SimpleString("import sys");
		PyRun_SimpleString("sys.path.append('./')");//这一步很重要,修改Python路径
		PyRun_SimpleString("import Sample");
		char *temp = "print(Sample.hello('52,589000'))";
		PyRun_SimpleString(temp);
		 *************************读txt文件*******************************
		//char* data = new char[20];
		//memset(data, 0, 20);
		//ifstream infile;
		//infile.open("data.txt");
		//infile >> data;
		// 在屏幕上写入数据


		string data;
		data = openFile();
		cout << data << endl;

		CString data;
		//CString data;
		//data = openFile();
		//cout << data << endl;

		//CString 变成 string str;
		//str = LPCSTR(data);
		//cout << str << endl;

	}
	Py_Finalize();//调用Py_Finalize,这个根Py_Initialize相对应的。

	return 0;
}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值