[C++/Python] 如何在C++中使用一个Python类? (Use Python-defined class in C++)
最近在做基于OpenCV的车牌识别, 其中需要用到深度学习的一些代码(Python), 所以一开始的时候开发语言选择了Python(祸患之源).
固然现在Python的速度不算太慢, 但你一定要用Python来操作图像, 实现某些算法的时候, 效率就变得非常重要. 可惜的是, Python在大多数算法实现中, 由于其循环操作实在是太慢, 导致实现的算法效率非常之低.
所以现在我要把深度学习中的一个类(分类器)转换到C++中, 在这个过程之前, 需要做一些test projects, 我主要参照的文章是: C++调用Python(3).
开发环境为 VS2012, WIN7 64.
所有代码都在最后放出, 这里先逐步讲解.
首先我们需要导入合适的头文件: Python.h, 它位于你的Python安装目录的include目录下. (2.6, 2.7版本实测通过)
使用VS的话, 可以按如下方法设置一下项目属性:
- 调试 -> xxx属性(最后一栏) -> VC++目录 -> 右侧库目录
- 增加C:\Python27\libs, 具体路径个人可能不同.
这样就完成了最基本的配置, 下面我们开始导入.py文件并使用它.
我们使用的.py文件非常简单, 代码如下:
#!/usr/bin/python
# Filename: testpy.py
class Person:
def sayHi(self):
print 'hi'
class Second:
def invoke(self,obj):
obj.sayHi()
def sayhi(name):
print 'hi',name;
注: 下述所有导入方法在导入失败时不会报错, 只会返回空指针.
第一步是导入.py文件:
- 使用PyObject* pModule来存储导入的.py文件模块, 调用的方法是PyImport_ImportModule(path): PyObject* pModule = PyImport_ImportModule("testpy");
- 使用PyObject* pDict来存储导入模块中的方法字典, 调用的方法是PyModule_GetDict(module): PyObject* pDict = PyModule_GetDict(pModule);
这样就完成了.py文件的导入.
第二步是导入已导入模块中的方法或类:
- 获取方法, 调用的方法是PyDict_GetItemString(dict, methodName): PyObject* pFunHi = PyDict_GetItemString(pDict, "sayhi");
- 获取类, 调用的方法同上, 注意红体部分的字符串对应于.py文件中的类/方法名: PyObject* pClassSecond = PyDict_GetItemString(pDict, "Second");
第三步是使用导入的方法或类:
- 使用方法, 调用PyObject_CallFunction(pFunc, "s", args)即可: PyObject_CallFunction(pFunHi, "s", "lhb");
- 使用类构造对象, 调用PyInstance_New(pClass, NULL, NULL)即可: PyObject* pInstanceSecond = PyInstance_New(pClassSecond, NULL, NULL); , 注意其中的pClassSecond为第二步.2中获取的类指针
- 使用类对象的方法, 调用PyObject_CallMethod(pInstance, methodname, "O", args)即可: PyObject_CallMethod(pInstanceSecond, "invoke", "O", pInstancePerson);
- 上述调用中的"s"和"O"代表的是参数列表的类型, 我们可以在 Py_BuildValue 找到所有的类型, 本文最后也附了此表.
最后不要忘记销毁这些对象: Py_DECREF(pointer);
下面是C++的实现代码, 代码来自于我参考的博客, 略有修改.
/*
* test.cpp
* Created on: 2010-8-12
* Author: lihaibo
*/
#include <C:/Python27/include/Python.h>
#include <iostream>
#include <string> int main(void) {
Py_Initialize(); // 启动虚拟机
if (!Py_IsInitialized())
return -;
// 导入模块
PyObject* pModule = PyImport_ImportModule("testpy");
if (!pModule) {
printf("Cant open python file!/n");
return -;
}
// 模块的字典列表
PyObject* pDict = PyModule_GetDict(pModule);
if (!pDict) {
printf("Cant find dictionary./n");
return -;
}
// 演示函数调用
PyObject* pFunHi = PyDict_GetItemString(pDict, "sayhi");
PyObject_CallFunction(pFunHi, "s", "lhb");
Py_DECREF(pFunHi);
// 演示构造一个Python对象,并调用Class的方法
// 获取Second类
PyObject* pClassSecond = PyDict_GetItemString(pDict, "Second");
if (!pClassSecond) {
printf("Cant find second class./n");
return -;
}
//获取Person类
PyObject* pClassPerson = PyDict_GetItemString(pDict, "Person");
if (!pClassPerson) {
printf("Cant find person class./n");
return -;
}
//构造Second的实例
PyObject* pInstanceSecond = PyInstance_New(pClassSecond, NULL, NULL);
if (!pInstanceSecond) {
printf("Cant create second instance./n");
return -;
}
//构造Person的实例
PyObject* pInstancePerson = PyInstance_New(pClassPerson, NULL, NULL);
if (!pInstancePerson) {
printf("Cant find person instance./n");
return -;
}
//把person实例传入second的invoke方法
PyObject_CallMethod(pInstanceSecond, "invoke", "O", pInstancePerson);
//释放
Py_DECREF(pInstanceSecond);
Py_DECREF(pInstancePerson);
Py_DECREF(pClassSecond);
Py_DECREF(pClassPerson);
Py_DECREF(pModule);
Py_Finalize(); // 关闭虚拟机
return ;
}
类型参照:
- s (string) [char *]
- Convert a null-terminated C string to a Python object. If the C string pointer is NULL, None is used.
- s# (string) [char *, int]
- Convert a C string and its length to a Python object. If the C string pointer is NULL, the length is ignored and None is returned.
- z (string or None) [char *]
- Same as s.
- z# (string or None) [char *, int]
- Same as s#.
- u (Unicode string) [Py_UNICODE *]
- Convert a null-terminated buffer of Unicode (UCS-2 or UCS-4) data to a Python Unicode object. If the Unicode buffer pointer is NULL, Noneis returned.
- u# (Unicode string) [Py_UNICODE *, int]
- Convert a Unicode (UCS-2 or UCS-4) data buffer and its length to a Python Unicode object. If the Unicode buffer pointer is NULL, the length is ignored and None is returned.
- i (integer) [int]
- Convert a plain C int to a Python integer object.
- b (integer) [char]
- Convert a plain C char to a Python integer object.
- h (integer) [short int]
- Convert a plain C short int to a Python integer object.
- l (integer) [long int]
- Convert a C long int to a Python integer object.
- B (integer) [unsigned char]
- Convert a C unsigned char to a Python integer object.
- H (integer) [unsigned short int]
- Convert a C unsigned short int to a Python integer object.
- I (integer/long) [unsigned int]
- Convert a C unsigned int to a Python integer object or a Python long integer object, if it is larger than sys.maxint.
- k (integer/long) [unsigned long]
- Convert a C unsigned long to a Python integer object or a Python long integer object, if it is larger than sys.maxint.
- L (long) [PY_LONG_LONG]
- Convert a C long long to a Python long integer object. Only available on platforms that support long long.
- K (long) [unsigned PY_LONG_LONG]
- Convert a C unsigned long long to a Python long integer object. Only available on platforms that support unsigned long long.
- n (int) [Py_ssize_t]
-
Convert a C Py_ssize_t to a Python integer or long integer.
New in version 2.5.
- c (string of length 1) [char]
- Convert a C int representing a character to a Python string of length 1.
- d (float) [double]
- Convert a C double to a Python floating point number.
- f (float) [float]
- Same as d.
- D (complex) [Py_complex *]
- Convert a C Py_complex structure to a Python complex number.
- O (object) [PyObject *]
- Pass a Python object untouched (except for its reference count, which is incremented by one). If the object passed in is a NULL pointer, it is assumed that this was caused because the call producing the argument found an error and set an exception. Therefore, Py_BuildValue()will return NULL but won’t raise an exception. If no exception has been raised yet, SystemError is set.
- S (object) [PyObject *]
- Same as O.
- N (object) [PyObject *]
- Same as O, except it doesn’t increment the reference count on the object. Useful when the object is created by a call to an object constructor in the argument list.
- O& (object) [converter, anything]
- Convert anything to a Python object through a converter function. The function is called with anything (which should be compatible withvoid *) as its argument and should return a “new” Python object, or NULL if an error occurred.
- (items) (tuple) [matching-items]
- Convert a sequence of C values to a Python tuple with the same number of items.
- [items] (list) [matching-items]
- Convert a sequence of C values to a Python list with the same number of items.
- {items} (dictionary) [matching-items]
- Convert a sequence of C values to a Python dictionary. Each pair of consecutive C values adds one item to the dictionary, serving as key and value, respectively.
If there is an error in the format string, the SystemError exception is set and NULL returned.
[C++/Python] 如何在C++中使用一个Python类? (Use Python-defined class in C++)的更多相关文章
- 如何在JAVA中实现一个固定最大size的hashMap
如何在JAVA中实现一个固定最大size的hashMap 利用LinkedHashMap的removeEldestEntry方法,重载此方法使得这个map可以增长到最大size,之后每插入一条新的记录 ...
- 如何在idea中引入一个新maven项目
如何在idea中引入一个新的maven项目,请参见如下操作:
- 如何在html中把一个图片或者表格覆盖在一张已有图片上的任意位置
如何在html中把一个图片或者表格覆盖在一张已有图片上的任意位置 <div style="position:relative;"> <img src=&quo ...
- (转)如何在Linux中统计一个进程的线程数
如何在Linux中统计一个进程的线程数 原文:http://os.51cto.com/art/201509/491728.htm 我正在运行一个程序,它在运行时会派生出多个线程.我想知道程序在运行时会 ...
- Kubernetes入门(四)——如何在Kubernetes中部署一个可对外服务的Tensorflow机器学习模型
机器学习模型常用Docker部署,而如何对Docker部署的模型进行管理呢?工业界的解决方案是使用Kubernetes来管理.编排容器.Kubernetes的理论知识不是本文讨论的重点,这里不再赘述, ...
- Python多进程库multiprocessing中进程池Pool类的使用[转]
from:http://blog.csdn.net/jinping_shi/article/details/52433867 Python多进程库multiprocessing中进程池Pool类的使用 ...
- Python的Django框架中forms表单类的使用方法详解
用户表单是Web端的一项基本功能,大而全的Django框架中自然带有现成的基础form对象,本文就Python的Django框架中forms表单类的使用方法详解. Form表单的功能 自动生成HTML ...
- Entity Framework 的小实例:在项目中添加一个实体类,并做插入操作
Entity Framework 的小实例:在项目中添加一个实体类,并做插入操作 1>. 创建一个控制台程序2>. 添加一个 ADO.NET实体数据模型,选择对应的数据库与表(Studen ...
- 在存放源程序的文件夹中建立一个子文件夹 myPackage。例如,在“D:\java”文件夹之中创建一个与包同名的子文件夹 myPackage(D:\java\myPackage)。在 myPackage 包中创建一个YMD类,该类具有计算今年的年份、可以输出一个带有年月日的字符串的功能。设计程序SY31.java,给定某人姓名和出生日期,计算该人年龄,并输出该人姓名、年龄、出生日期。程序使用YM
题目补充: 在存放源程序的文件夹中建立一个子文件夹 myPackage.例如,在“D:\java”文件夹之中创建一个与包同名的子文件夹 myPackage(D:\java\myPackage).在 m ...
随机推荐
- 19 中山重现赛 1002 triangle
题意:给一组数据a[0]...a[n], n<5e6, a[i]<2^31-1(1e9)判断是否存在三角形数 首先想到的是排序,若a[i]+a[i+1]>a[i+2] , 则存在三 ...
- 最接近的三数之和(java实现)
题目: 给定一个包括 n 个整数的数组 nums 和 一个目标值 target.找出 nums 中的三个整数,使得它们的和与 target 最接近.返回这三个数的和.假定每组输入只存在唯一答案. 例如 ...
- acm
给定一组数字,一组有9个数字,将这9个数字填写到3*3的九宫格内:使得横,竖,斜对角一条线上的三个数字之和相等:如果无解则打印无解: #include <iostream> #includ ...
- 若依项目整合eCharts实现图表统计功能
eCharts是一款强大的图表统计工具,具体介绍可查看其官网 http://echarts.baidu.com/echarts2/index.html 下面记录一下如何在若依项目中使用eCharts. ...
- 模糊测试(fuzzing)是什么
一.说明 大学时两个涉及“模糊”的概念自己感觉很模糊.一个是学数据库出现的“模糊查询”,后来逐渐明白是指sql的like语句:另一个是学专业课时出现的“模糊测试”. 概念是懂的,不外乎是“模糊测试是一 ...
- SQL注入理解与防御
一.说明 sql注入可能是很多学习渗透测试的人接触的第一类漏洞,这很正常因为sql注入可能是web最经典的漏洞.但在很多教程中有的只讲‘或and 1=1.and 1=2有的可能会进一步讲union s ...
- SQL语句中Left join,right join,inner join用法
转载于:https://blog.csdn.net/lichkui/article/details/2002895 一.先看一些最简单的例子 例子 Table Aaid adate 1 ...
- 除了Udacity,全球最聪明的那群人还上哪些网站?
01. ***,与世界相连 WikiWand——打开维基百科的新方式 http://www.wikiwand.com/ InsightfulQuestions(subreddit)——跨越界限的智力讨 ...
- bootstrap表格鼠标悬停与状态类
今天在学习的过程中遇到在表格一章中 鼠标悬停 与 状态类 无效的问题,是因为在css文件中默认颜色都为白色造成的,解决方式如下: 在bootstrap文件夹中找到bootstrap.css文件(我的版 ...
- Problem A: 平面上的点和线——Point类、Line类 (I)
Description 在数学上,平面直角坐标系上的点用X轴和Y轴上的两个坐标值唯一确定,两点确定一条线段.现在我们封装一个“Point类”和“Line类”来实现平面上的点的操作. 根据“append ...