我为 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/