你将学到什么

  • 在C++中调用Python代码时的传参问题

基础类型

继续使用前面的项目,但是先修改下Python脚本(zoo.py),添加AddStr函数,分别针对整数、浮点数和字符串参数的测试

def Add(x, y):
print(x + y) def Str(s):
print("Output: " + s) if __name__ == '__main__':
pass

然后修改下main.cpp源文件

#include <iostream>
#include <boost/python.hpp>
#include "boost_wrapper.h" using namespace boost::python;
using namespace boost::python::detail; int main()
{
Py_Initialize();
if (!Py_IsInitialized())
{
std::cout << "Initialize failed" << std::endl;
return -1;
} try
{
object sys_module = import("sys");
str module_directory(".");
sys_module.attr("path").attr("insert")(1, module_directory);
object module = import("zoo");
module.attr("Add")(object(2), object(4));
module.attr("Add")(object(3.0f), object(4));
module.attr("Str")(object("test"));
}
catch (const error_already_set&)
{
PyErr_Print();
}
Py_Finalize();
return 0;
}

编译并测试

# cd build
# make
# ./core
6
7.0
Output: test

类实例

首先修改下Python脚本(zoo.py),添加Pet函数,针对类实例参数的测试,其参数为Animal类实例

import boost

def Pet(obj):
obj.eat("meat")
print(type(obj))
print(isinstance(obj, boost.Animal)) if __name__ == '__main__':
pass

然后修改下main.cpp源文件

#include <iostream>
#include <boost/python.hpp>
#include "boost_wrapper.h" using namespace boost::python;
using namespace boost::python::detail; int main()
{
Py_Initialize();
if (!Py_IsInitialized())
{
std::cout << "Initialize failed" << std::endl;
return -1;
} try
{
object sys_module = import("sys");
str module_directory(".");
sys_module.attr("path").attr("insert")(1, module_directory);
object module = import("zoo");
object o = class_<AnimalWrap, boost::noncopyable>("Animal", init<std::string>())
.def("call", &Animal::call)
.def("move", &Animal::move)
.def("eat", &Animal::eat)("Wangcai");
module.attr("Pet")(o);
}
catch (const error_already_set&)
{
PyErr_Print();
}
Py_Finalize();
return 0;
}

编译并测试

# cd build
# make
# ./core
Wangcai: eat meat
<class 'Animal'>
False

标准库

首先修改下Python脚本(zoo.py),添加tListtDicttTuple函数,分别用于测试std::vector/std::liststd::map以及数组

def tList(l):
for i in l:
print(i) def tDict(d):
for k in d:
print(str(k) + ":" + str(d[k])) def tTuple(t):
for i in t:
print(i) if __name__ == '__main__':
pass

然后修改下main.cpp源文件

#include <iostream>
#include <vector>
#include <boost/python.hpp>
#include "boost_wrapper.h" using namespace boost::python;
using namespace boost::python::detail; int main()
{
Py_Initialize();
if (!Py_IsInitialized())
{
std::cout << "Initialize failed" << std::endl;
return -1;
} try
{
object sys_module = import("sys");
str module_directory(".");
sys_module.attr("path").attr("insert")(1, module_directory);
object module = import("zoo");
list l;
l.append(2);
l.append("dog");
std::vector<int> v = {3, 4, 5, 6};
for (auto item : v)
l.append(item);
module.attr("tList")(l);
dict d;
d.setdefault("fwd", 28);
d.setdefault("xb", 26);
module.attr("tDict")(d);
tuple t = make_tuple("fwd", 28, "xb", 26);
module.attr("tTuple")(t);
}
catch (const error_already_set&)
{
PyErr_Print();
}
Py_Finalize();
return 0;
}

编译并测试

# cd build
# make
# ./core
2
dog
3
4
5
6
fwd:28
xb:26
fwd
28
xb
26

总结

类实例还是尽量导出后在Python脚本中创建,如果在C++代码中创建,然后传入Python脚本的话,它的类型并不是boost.Animal,这就导致无法使用isinstance来区分对象。

Boost Python学习笔记(三)的更多相关文章

  1. Python 学习笔记三

    笔记三:函数 笔记二已取消置顶链接地址:http://www.cnblogs.com/dzzy/p/5289186.html 函数的作用: 給代码段命名,就像变量給数字命名一样 可以接收参数,像arg ...

  2. Boost Python学习笔记(四)

    你将学到什么 在Python中调用C++代码时的传参问题 基础类型 Python的字符串是常量,所以C++函数参数中的std::string &必须为const 修改源文件(main.cpp) ...

  3. Boost Python学习笔记(五)

    你将学到什么 在C++中调用Python代码时的返回值问题 基础类型 修改Python脚本(build/zoo.py) def rint(): return 2 def rstr(): return ...

  4. Boost Python学习笔记(二)

    你将学到什么 如何在Python中调用C++代码 如何在C++中调用Python代码 在Python中调用C++代码 首先定义一个动物类(include/animal.h) #pragma once ...

  5. webdriver(python) 学习笔记三

    知识点:简单的对象定位 对象的定位应该是自动化测试的核心,要想操作一个对象,首先应该识别这个对象.一个对象就是一个人一样,他会有各种的特征(属性),如比我们可以通过一个人的身份证号,姓名,或者他住在哪 ...

  6. python学习笔记三--字典

    一.字典: 1. 不是序列,是一种映射, 键 :值的映射关系. 2. 没有顺序和位置的概念,只是把值存到对应的键里面. 3. 通过健而不是通过偏移量来读取 4. 任意对象的无序集合 5. 可变长,异构 ...

  7. Python学习笔记三

    一. 为什么要使用函数? 函数可以方便阅读代码. 函数可以减少重复代码. 函数可以减少管理操作,减少修改操作. 二. 函数分类: 内置函数:len()   sum()   max()   min() ...

  8. python学习笔记(三)、字典

    字典是一种映射类型的数据类型.辣么什么是映射呢?如果看过<数据结构与算法>这一本书的小伙伴应该有印象(我也只是大学学习过,嘻嘻). 映射:就是将两个集合一 一对应起来,通过集合a的值,集合 ...

  9. Python学习笔记三:模块

    一:模块 一个模块就是一个py文件,里面定义了一些业务函数.引用模块,可以用import语句导入.导入模块后,通过 模块.函数名(参数)  来使用模块中的函数.如果存在多个同名模块,则前面模块名需要加 ...

随机推荐

  1. HTML5坦克大战1

    在JavaScript中,不要在变量为定义之前去使用,这样很难察觉并且无法运行. 颜色不对. 当我的坦克移动时,敌人坦克消失. tankGame3.html <!DOCTYPE html> ...

  2. 智课雅思词汇---十四、ante,anti不仅是词根还是前缀

    智课雅思词汇---十四.ante,anti不仅是词根还是前缀 一.总结 一句话总结:来源于拉丁语 ante 前.词根ant 为 anti 的变体.ante,anti不仅是词根还是前缀. 词根:ante ...

  3. python3 字符串属性(一)

    python3 字符串属性 >>> a='hello world' >>> dir(a) ['__add__', '__class__', '__contains_ ...

  4. 二 Django框架,urls.py模块,views.py模块,路由映射与路由分发以及逻辑处理——url控制器

    Django框架,urls.py模块,views.py模块,路由映射与路由分发以及逻辑处理——url控制器 这一节主讲url控制器 一.urls.py模块 这个模块是配置路由映射的模块,当用户访问一个 ...

  5. Linux Shell 判断块设备节点是否存在

    /************************************************************************* * Linux Shell 判断块设备节点是否存在 ...

  6. FFmpeg基础知识之————H264编码profile & level控制

    H.264有四种画质级别,分别是baseline, extended, main, high: 1.Baseline Profile:基本画质.支持I/P 帧,只支持无交错(Progressive)和 ...

  7. ngCookies都做了什么

    根据官方的api文档,ngCookies的$cookieStore服务,提供了这样几个方法: 1.get(key); 2.put(key, value); 3.remove(key); 以上方法都是对 ...

  8. MySQL Explain详解(转)

    explain SELECT a.* FROM test a,(select id from test where level_id <=4 order by aa_id limit 24300 ...

  9. 2013 蓝桥杯校内选拔赛 java本科B组(题目+答案)

    一.标题:正则表示     正则表达式表示了串的某种规则或规律.恰当地使用正则表达式,可以使得代码简洁.事半功倍.java的很多API都支持正则表达式作为参数.其中的String.split就是这样. ...

  10. POJ 2017 No Brainer(超级水题)

    一.Description Zombies love to eat brains. Yum. Input The first line contains a single integer n indi ...