python - 包装的 C++ 函数的输入字符串不会更改 SWIG

标签 python c++ swig

我为 C++ 库制作了 Python 包装器。

我的库:

%module mylib
%include <std_string.i>

%{
    #include "mylib.h"

%}
%apply const std::string & {std::string &};
%apply std::string & {std::string &};

int getResult(const std::string& path, std::string& result);

mylib.h:

#pragma once

#include <string>

myEnum {foo=0, bar};
myEnum getResult(const std::string& path, std::string& result);

使用以下命令生成_mylib.so 后:

g++ -fPIC -Wall -Wextra -shared mylib_wrap.cxx -o _mylib.so -L. -lmylib -I/usr/include/python2.7/ -lpython2.7

我接下来要做的是:

LD_LIBRARY_PATH=. python Python 2.7.2 (default, Dec  6 2016, 10:43:39) 
[GCC 4.8.4] on linux4
Type "help", "copyright", "credits" or "license" for more information.
>>> import _mylib
>>> result= ""
>>> x = _mylib.getResult("somePath",result)

执行我的函数后,x 返回方法的正确响应。我的函数也有控制台输出。但结果字符串没有改变。 如果我用“some text”初始化结果字符串,并再次调用我的函数,print result 返回 “some text”。我做错了什么?

最佳答案

让它在您的界面中工作的最简单方法是使用 %inline 创建一个返回结果的重载:

%module mylib
%include <std_string.i>

%{
    #include "mylib.h"
%}

%inline %{
    int getResult(const std::string& path) {
        std::string temp;
        const int ret = getResult(path, temp);
        if (ret != good) abort(); // TODO exceptions
        return temp;
    }
%}

您甚至不需要向 SWIG 显示 getResult 的真实版本。

还有其他选项(例如,使用带有 numinputs=0 的输入类型映射和 argout 类型映射来修改返回值),但它们更复杂并且通常更难移植到其他语言。

关于python - 包装的 C++ 函数的输入字符串不会更改 SWIG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40997992/

相关文章:

python - 如何在绘图中添加粗体注释文本

python - Jupyter 实验室未打印 sklearn 模型的所有参数

java - 如何为单个 C 函数生成多个包装器?

python - 使用 Networkx 在图形的 matplotlib 上高效制作动画

Python 文件附加错误

c++ - OpenCV和Matlab中不同的模板匹配结果

c++ - 多维 std::vector (C++) 的内存分配

c++ - 我在 visual studio 的调用堆栈上看到的这些十六进制字符串是什么

c++ - Adobe Alchemy 编译的 SWC - 不确定如何为 FlasCC 编译库

python - 为什么我会丢失 SWIG、C++、python 的异常