包装的 C++ 函数的输入信号不会改变 SWIG [英] Input sting for wrapped C++ function doesn't changing SWIG
问题描述
我为 C++ 库制作 Python 包装器.
I make Python wrapper for C++ library.
mylib.i:
%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 后:
After generating _mylib.so with following command:
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"
.我做错了什么?
After execution of my function, x
returns right respond of method. Also I have console output from my function. But result string doesn't changing.
If I init result string with "some text", and call my function again, print result
return "some text"
. What I'm doing wrong?
推荐答案
让这个在你的界面中工作的最简单的方法是使用 %inline
创建一个重载来返回结果:
The simplest way to get this to work inside your interface is to use %inline
to create an overload that returns the result instead:
%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
的真实版本.
You don't even need to show SWIG the real version of getResult
.
还有其他选项(例如,使用 numinputs=0 的输入类型映射和 argout 类型映射来修改返回值),但它们更复杂,通常对其他语言的移植性较差.
There are other options (e.g. use an input typemap with numinputs=0 and an argout typemap to modify the return value), but they're more complicated and generally less portable to other languages.
这篇关于包装的 C++ 函数的输入信号不会改变 SWIG的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!