【发布时间】:2015-05-19 17:01:02
【问题描述】:
免责声明,我是一个 swig 和 python 菜鸟
我有自己的 c++ 库,我将它包装在 python 中与 swig 一起使用。
我的 c++ 类是这样的:
public MyCppClass()
{
public:
void MyFunction(char* outCharPtr, string& outStr, int& outInt, long& outLong)
{
outCharPtr = new char[2];
outCharPtr[0] = "o";
outCharPtr[1] = "k";
outStr = "This is a result";
outInt = 1;
outLong = (long)12345;
}
}
现在我用 swig 包装这个类,并说这个模块叫做 MyClass。
我想在 python 中实现的是以下代码(或者说伪代码,因为如果它是它会工作的代码)和输出:
import module MyClass
from MyClass import MyCppClass
obj = MyCppClass();
outCharPtr = "";
outStr = "";
outInt = 0;
outLong = 0;
obj.MyFunction(outCharPtr, outStr, outInt, outLong);
print(outCharPtr);
print(outStr);
print(outInt);
print(outLong);
我想要的输出是:
>>>Ok
>>>This is a result
>>>1
>>>12345
我正在使用 python 3.4
如果这是基本的问题,我真的很抱歉,但我已经花了大约 8 个小时来解决这个问题,但还是什么都想不出来。
任何帮助将不胜感激。
谢谢。
【问题讨论】:
-
一个问题是Python没有out参数。您已经创建了不可变的
str和intPython 对象,因此所需的语法将不起作用。对象不能改变。 SWIG 可以为您做的是将 C/C++ 输出参数转换为返回值的元组。例如,outCharPtr,outStr,outInt,outLong = obj.MyFunction()。 -
非常感谢您的澄清!
标签: c++ python-3.x pass-by-reference swig