python - 如何编写 C++ 代码以使用 SWIG 在 python 提示符中打印变量值

标签 python c++ swig

我是 SWIG 的新手,想包装 C++ 类并在 python 中使用它。作为练习,我正在编写一个 Vector 类(类似于 STL 中的类)。现在我想在python环境中输入 vector 名称后打印出 vector 的元素。

它是这样的:

>>>v
1 2 3 4

我怎样才能做到这一点?

最佳答案

您可以在 .i 文件中使用 %template 指令和 std_vector.i 库。

引用:http://www.swig.org/Doc3.0/SWIGDocumentation.html#Library_std_vector

myModule.h文件(C++头文件)

#include <vector>

std::vector<int> GetVectorInt();

myModule.cpp文件(C++源文件)

std::vector<int> GetVectorInt()
{
    std::vector<int> vOutput;

    for(int i = 0; i < 10; i++)
        vOutput.push_back(i);

    return vOutput;
}

myModule.i 文件(SWIG 接口(interface)文件)

%module myModule
%{
#include "myModule.h"
%}

%include "std_vector.i"

%template(IntVector) std::vector<int>;

%include "myModule.h"

Python输出

>>> my_vector = myModule.GetVectorInt()
>>> my_vector
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

关于python - 如何编写 C++ 代码以使用 SWIG 在 python 提示符中打印变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25775244/

相关文章:

python - 如何将 Python 中的字节对象传递给用 Swig 包装的 C++ 函数?

c# - 尝试使用 swig 将 C++ 库与 C# 链接 - 不会让我将对 resulging dll 的引用添加到 C# 项目

python - 如何使用另一个 python 脚本文件中的参数执行 python 脚本文件

python - 生成可变长度哈希

python - 推特/通用分类训练语料库

python - pandas:如何查看(参数)字符串是否在 pandas 元素中的字符串列表中(有点反向 isin)

c++ - C/C++ - 生成一个随机字符串覆盖以前的(见下面的代码)

c++ - 以螺旋方式修改数组

c++ - MSVC 中的 "interface"关键字是什么?

python - swig shared_ptr 导致不透明对象