从Python interp调用SWIG生成的代码

2024-09-30 18:35:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用SWIG来调用Python中C++对象的成员函数。目前我有一个小示例类,它使用一个吸收器和设置器来修改C++类的成员变量。这里是C++头文件:

#ifndef _square_
#define _square_
#include <iostream>

class Square
{
 private:
    double x;
    double y;
    const char *name;

 public:
    void setName(const char*);
    const char* getName();
    Square() {
        name = "construct value";
    };
};
#endif

以下是.cpp实现文件:

^{pr2}$

还有广场。我要申请斯威格:

%module Square
%{
#include "Square.h"
%}

%include "Square.h"

SWIG似乎产生了正方形_包装.cxx文件没有问题,并且生成的对象文件似乎链接良好:

$ swig -python -c++ Square.i
$ g++ -c -fpic Square.cxx Square_wrap.cxx -I/usr/include/python2.7
$ g++ -shared Square.o Square_wrap.o -o _Square.so

下面是一些Python示例来测试结果:

$ cat test2.py
#!/usr/bin/python
import Square

s = Square.Square()

print s.getName()
s.setName("newnametest")
print s.getName()

如果我在Python解释器中运行此命令,则一切正常:

$ python test2.py
construct value
newnametest

但是如果我通过Python的CLI以交互方式输入到测试行中,则无法正常工作:

$ python
Python 2.7.4 (default, Apr 19 2013, 18:28:01) 
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import Square
>>> 
>>> s = Square.Square()
>>> 
>>> print s.getName()
construct value
>>> s.setName("newnametest")
>>> print s.getName()

>>> s.getName()
'<stdin>'
>>> s.setName('newnametest')
>>> s.getName()
''
>>> s.setName("newnametest")
>>> s.getName()
''

Python对Python脚本文件的处理与CLI有什么不同吗?还是我在某种程度上滥用了SWIG生成的Python接口?任何关于如何调试或理解隐藏问题的提示都将不胜感激。在


Tags: 文件对象includevaluecxx成员constructswig
1条回答
网友
1楼 · 发布于 2024-09-30 18:35:28

就我所见,您只是将引用存储在cpp文件(this->name = name)上。复制它会很好,因为很有可能字符串不够持久,只是在函数返回后被丢弃(之后再进行垃圾收集)。这将解释为什么在脚本中它起作用(两个调用之间没有GCollection,也没有发生任何其他事情)。在

尝试使用strdup或使用std::string制作副本。在

相关问题 更多 >