python 构造函数传参_C++和python混合编程之在python类构造函数中传参方法
C++和python混合编程
零、前言
一、说明
二、测试代码
1、C++代码
2、python代码
三、运行结果
零、前言
C++是一门高效率的语言,Python是一门简单易学的脚本语言,现在Python非常火,这两者的强大结合能碰撞出很强大的火花!一起来看看吧!
一、说明
C++项目中用到python相关的知识,这两天研究了一下C++与python的混合编程,网上有很多这方面的介绍,但是怎么使用python类的构造函数中传参的介绍却没有,这里研究一下,分享出来。(C++和python相互调用的相关接口查询https://docs.python.org/2/index.html)
二、测试代码
1、C++代码
/*=================CplusUsePython.h====================*/
#ifndef CPLUSUSEPYTHON_H
#define CPLUSUSEPYTHON_H
#include #include using namespace std;
class CplusUsePython
{
public:
CplusUsePython();
~CplusUsePython();
static CplusUsePython* instance()
{
static CplusUsePython instance;
return &instance;
}
// 初始化相关操作
int init(const string pyFilePath, const string pyFileNameNoSuffix);
// C++调用python函数
int CCallFunction(const string pyFuncName, const string message);
// C++调用python类中的函数
int CCallClassFunc(const string pyFuncName, const string name, const int age);
private:
PyObject *pName;
PyObject *pModule;
PyObject *pFunc;
PyObject *pArgs;
PyObject *pClass;
PyObject *pInstance;
};
#endif // CPLUSUSEPYTHON_H
/*=================CplusUsePython.cp====================*/
#include "CplusUsePython.h"
#include CplusUsePython::CplusUsePython()
{
}
CplusUsePython::~CplusUsePython()
{
if (Py_IsInitialized()) {
if (pName) Py_DECREF(pName);
if (pArgs) Py_DECREF(pArgs);
if (pModule) Py_DECREF(pModule);
if (pFunc) Py_DECREF(pFunc);
if (pClass) Py_DECREF(pClass);
if (pInstance) Py_DECREF(pInstance);
Py_Finalize();
}
}
//************************************
// 函数名称: init
// 函数说明:初始化相关操作
// 返 回 值: int
// 参 数: const string pyFilePath
// 参 数: const string pyFileNameNoSuffix
// 作 者:ISmileLi
// 作成日期:2018/11/25
// 修改记录:
//************************************
int CplusUsePython::init(const string pyFilePath, const string pyFileNameNoSuffix)
{
int ret = 0;
if (pyFilePath.empty() || pyFileNameNoSuffix.empty())
return -1;
Py_Initialize();
pName = NULL;
pModule = NULL;
pFunc = NULL;
pArgs = NULL;
pClass = NULL;
pInstance = NULL;
// 判断初始化是否成功
if (!Py_IsInitialized())
return -2;
// 调用python中需要使用的模块
ret = PyRun_SimpleString("import sys");
if (ret != 0)
{
// 导入失败,关闭python调用
Py_Finalize();
return -3;
}
// 导入python文件的相关操作
if (ret == 0)
{
stringstream strpycmd;
strpycmd << "sys.path.append('" << pyFilePath << "')";
ret = PyRun_SimpleString(strpycmd.str().c_str());
}
if (ret != 0)
{
Py_Finalize();
return -4;
}
pName = PyString_FromString(pyFileNameNoSuffix.c_str());
if ((pModule = PyImport_Import(pName)) == NULL || pName == NULL)
{
Py_Finalize();
return -5;
}
return 0;
}
//************************************
// 函数名称: CCallFunction
// 函数说明:C++调用python中的函数
// 返 回 值: int
// 参 数: const string pyFuncName
// 参 数: const string message
// 作 者:ISmileLi
// 作成日期:2018/11/25
// 修改记录:
//************************************
int CplusUsePython::CCallFunction(const string pyFuncName,const string message)
{
if (pyFuncName.empty() || message.empty())
{
return -1;
}
pFunc = PyObject_GetAttrString(pModule, pyFuncName.c_str());
if(!pFunc)
{
return -2;
}
// 调用python函数,s表示传入参数是字符串类型
PyObject *pRet = PyObject_CallFunction(pFunc, "s", (char*)message.c_str());
if(pRet)
{
Py_DECREF(pRet);
}
else
{
return -3;
}
return 0;
}
//************************************
// 函数名称: CCallClassFunc
// 函数说明:C++调用python类中的函数
// 返 回 值: int
// 参 数: const string pyFuncName
// 参 数: const string name
// 参 数: const string age
// 作 者:ISmileLi
// 作成日期:2018/11/25
// 修改记录:
//************************************
int CplusUsePython::CCallClassFunc(const string pyFuncName,const string name, const int age)
{
if (pyFuncName.empty() || name.empty() || age <= 0)
{
return -1;
}
// 向Python传参数是以元组(tuple)的方式传递的
pArgs = PyTuple_New(2);
// PyObject* Py_BuildValue(char *format, ...) 将C++的变量转换成一个Python对象
// s 表示字符串,i 表示整型变量,f 表示浮点数
PyTuple_SetItem(pArgs, 0, Py_BuildValue("s", name.c_str()));
PyTuple_SetItem(pArgs, 1, Py_BuildValue("i", age));
// 增加支持调用类中方法的操作
pClass = PyObject_GetAttrString(pModule,"ISmileLi"); // DrawPic为类的名字
if(!pClass)
{
return -2;
}
// 传入python构造函数中的两个参数
pInstance = PyInstance_New(pClass,pArgs,NULL);
if(!pInstance)
{
return -3;
}
// 调用类中的函数
pFunc = PyObject_CallMethod(pInstance,(char*)pyFuncName.c_str(),NULL,NULL);
if(!pFunc)
{
return -4;
}
return 0;
}
/*=================main.c================*/
#include #include #include #include "CplusUsePython.h"
using namespace std;
int main ()
{
// C++和python相互调用的相关接口查询https://docs.python.org/2/index.html
string pyFilePath = "/work/test/testC++/test_C_use_Python";
int ret = CplusUsePython::instance()->init(pyFilePath,"ISmileLi");
if(ret != 0)
{
cout << "init failure!" << endl;
}
ret = CplusUsePython::instance()->CCallFunction("print_message","this is test C++ use python!");
ret = CplusUsePython::instance()->CCallClassFunc("print_name","LiSa",18);
ret = CplusUsePython::instance()->CCallClassFunc("print_age","LiSa",18);
ret = CplusUsePython::instance()->CCallClassFunc("print_name_age","LiSa",18);
return 0;
}
2、python代码
#filename: ISmileLi.py
# -*- coding: utf-8 -*-
class ISmileLi:
def __init__(self,name,age):
self.name = name
self.age = age
def print_name(self):
print("===in function print_name===")
print("name:",self.name)
def print_age(self):
print("===in function print_age===")
print("age:",self.age)
def print_name_age(self):
print("===in function print_name_age===")
print("name:%s age:%d" % (self.name,self.age))
def print_message(message):
print("===in function print_message===")
print("message:",message)
三、运行结果
说明:由于我也不擅长python,如有错误欢迎指正。
python 构造函数传参_C++和python混合编程之在python类构造函数中传参方法相关推荐
- python随机生成字母和数字的混合字符串_用python生成数字、字母和特殊字符混合的字符串...
1.生成固定长度的数字.字母和特殊字符混合的字符串(定义一个类,写在方法里) import string import random class test(): def function(self): ...
- python flask高级编程之restful_('Python Flask高级编程之RESTFul API前后端分离精讲',),全套视频教程学习资料通过百度云网盘下载...
资源详情 r n t某课网好评度100%的Python Flask高级编程之RESTFul API前后端分离精讲 r n t t t第1章 随便聊聊 r n t t t聊聊Flask与Django,聊 ...
- 与小卡特一起学python 豆瓣_《父与子的编程之旅:与小卡特一起学Python》
原标题:<父与子的编程之旅:与小卡特一起学Python> 内容简介 本书是一本家长与孩子共同学习编程的入门书.作者是一对父子,他们以Python语言为例,详尽细致地介绍了Python如何安 ...
- 《从零开始学Swift》学习笔记(Day 70)——Swift与Objective-C混合编程之Swift与Objective-CAPI映射...
原创文章,欢迎转载.转载请注明:关东升的博客 Swift与Objective-C API映射 在混合编程过程中Swift与Objective-C调用是双向的,由于不同语言对于相同API的表述是不同的, ...
- c++类指针赋值表达式必须是可修改的左值_C生万物,编程之本!(c语言基础笔记)
c语言入门 C语言一经出现就以其功能丰富.表达能力强.灵活方便.应用面广等特点迅速在全世界普及和推广.C语言不但执行效率高而且可移植性好,可以用来开发应用软件.驱动.操作系统等.C语言也是其它众多高级 ...
- java二维数组如何传参_C语言中二维数组作为函数参数来传递的三种方法
c语言中经常需要通过函数传递二维数组,有三种方法可以实现,如下: 方法一, 形参给出第二维的长度. 例如: #include void func(int n, char str[ ][5] ) { i ...
- Python自动化运维之15、网络编程之socket、socketserver、select、twisted
一.TCP/IP相关知识 TCP/UDP提供进程地址,两个协议互不干扰的独自的协议 TCP :Transmission Control Protocol 传输控制协议,面向连接的协议,通信前需要建立通 ...
- 详解Python类定义中的各种方法
首先应该明确,在面向对象程序设计中,函数和方法这两个概念是有本质区别的.方法一般指与特定实例绑定的函数,通过对象调用方法时,对象本身将被作为第一个参数传递过去,普通函数并不具备这个特点. >&g ...
- 学习参考《父与子的编程之旅python【第二版】》高清中文版PDF+高清英文版PDF+源代码...
对于初步接触编程语言的朋友,推荐看一看<父与子的编程之旅第2版>,对于完全编程零基础的很友好! 图文并茂,过多的文字堆垒很容易让人产生厌倦情绪,也更容易让人产生放弃的想法.使用了大量插图, ...
最新文章
- 你知道吗?你可以在异常中解退调用栈
- 搜狗输入法漏洞获取系统权限0day再述
- Firebird数据库系统的开发团队
- Delphi绘制Alpha图像的函数
- AIC-赤池信息准则、BIC-贝叶斯信息准则
- postgresql目录
- iOS仿支付宝芝麻信用仪表盘效果
- lubridate | 日期类型数据的转换
- python库skimage 绘制二值图像的凸壳
- iPhone设备字体详解
- tkmybatis 枚举值处理
- MATLAB-imrotate函数
- pythonobject转int_python – Pandas:将date’object’转换为int
- Rhythmbox 下中文的音乐文件显示成乱码解决办法
- 海普完成数千万元战略融资
- Undertow文件上传10M以上抛异常UT000020: Connection terminated as request was larger than 10485760
- 【洛谷 P5850】 calc加强版(生成函数+NTT)
- 云主机装黑果实践(6):处理云主机上变色龙启动后置过程:驱动和黑屏
- 自学python入门训练营 李笑来_1901090043-自学训练营学习9群-PYTHON入门
- 使用zookeeper获取brokers的信息