使用 SWIG 对 C++ 进行 Python 包装。参数类型无法识别

标签 python c++ wrapper swig

我正在尝试在 Linux 上使用 SWIG 围绕 C++ 代码构建 Python 包装器,但我不确定包装器是否已正确创建。例如,这是一个小问题(在我的较大项目中)。

假设我有一个名为 message.cpp 的文件

消息.cpp

#include <iostream>

#include "message.hpp"

void warning (std::string message) {
  using std::cout;
    cout << "\n!! WARNING!  " << message << " !!\n";
}

对应的头文件为:

消息.hpp

#include <string> 
#include <fstream>   // file I/O
#include <sstream>
#include <iostream>

void warning (const std::string message);

为了通过 SWIG 传递它,我有以下 SWIG 输入文件:

消息.i

%module message

%{
#include "message.hpp"
%}

%include "message.hpp"

从 Linux 终端,我使用以下命令创建包装器:

$ swig -c++ -python message.i

$ g++ -fpic -c message.hpp message_wrap.cxx message.cpp -I/usr/include/python2.7/ -I/usr/include

$ gcc -shared message_wrap.o message.o -o _message.so -lstdc++

命令提示符下的所有 3 个步骤都通过,终端上没有任何错误,并且生成了以下文件,没有任何提示:

message_wrap.cxx
message_wrap.o
message.o
message.py
message.hpp.gch
_message.so

然后,我尝试通过在 Linux 终端上输入以下命令(位于同一目录中)来测试 Python 包装器:

$ python
Python 2.7.17
[GCC 7.4.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import _message
>>> _message.warning("SampleMessage")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: in method 'warning', argument 1 of type 'std::string const'

我期望它只显示行警告! SampleMessage 在终端上,但它崩溃了。所以看来出了什么问题。有人可以指导我问题出在哪里吗?

最佳答案

您的声明和实现不匹配(缺少 const),您应该导入 message 而不是 _message。综上所述,您缺少的是:

%include "std_string.i"

在 .i 中包含 message.hpp 之前。这将提供将 Python str 转换为 C++ std::string 所需的类型映射。

关于使用 SWIG 对 C++ 进行 Python 包装。参数类型无法识别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59637794/

相关文章:

C++ 在字节 vector 和 wstring 之间转换

java - 如何知道何时在 RequestWrapper 对象中转发请求

java - 使用 Java 包装 C++

php - 如何从 php ://temp wrapper 中删除文件

python - 在 python 2.4.3 中打开的替代方法是什么

python - 在分组 DataFrame 上应用不同聚合的最佳方法

c++从头文件vs在cpp文件中访问变量

C++ 字符串数组切片

python - 用给定列表的元素替换出现的子字符串

python - 无法在 conda 中安装 matplotlib