【发布时间】:2015-05-07 07:02:16
【问题描述】:
我正在研究如何使用 swig 为我的 python 代码进行 C 扩展。我使用从网站获得的代码作为示例。 这是我的代码:
example.c
#include <time.h>
double My_variable = 3.0;
int fact(int n) {
if (n <= 1) return 1;
else return n*fact(n-1);
}
int my_mod(int x, int y) {
return (x%y);
}
example.h
#ifndef EXAMPLE_H_
#define EXAMPLE_H_
extern double My_variable;
extern int fact(int n);
extern int my_mod(int x, int y);
#endif
example.i
%module example
%{
/* Put header files here or function declarations like below */
#define SWIG_FILE_WITH_INIT
#include "example.h"
%}
%#include "example.h"
生成文件
all:
rm -f *.so *.o *_wrap.* *.pyc
swig -python example.i
gcc -c -fPIC example_wrap.c -I/usr/include/python2.7
gcc -shared example_wrap.o -o _example.so
clean:
rm -f *.so *.o *_wrap.* *.pyc
test.py
import example
print str(example.fact(2))
test.py 用于检查扩展是否有效。但是当我运行 test.py 时,它会输出:
Traceback (most recent call last):
File "test.py", line 3, in <module>
print str(example.fact(2))
AttributeError: 'module' object has no attribute 'fact'
这是我使用 dir(example) 时的输出:
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '_example', '_newclass', '_object', '_swig_getattr', '_swig_property', '_swig_repr', '_swig_setattr', '_swig_setattr_nondynamic']
出现此输出的原因是什么?
如果我想让程序运行成功,我该怎么做?
【问题讨论】:
-
也许:“gcc -shared -o _example.so example_wrap.o”可以解决问题,通常链接到库的内容放在.so之后。
-
@Tony 还是不行。
-
好的,如果链接不正确,则可能是“gcc -shared -Wl,-soname, _example.so -o _example.so example_wrap.o”。抱歉,如果它没有帮助,我不使用 SWIG,但我在使用 boost.python 时遇到了类似的问题,它们与编译有关。