我正在使用python和swig。cpp文件包含一个变量int step=0;和一个使用变量void test();的函数,当我在Python语言中调用该函数时,我得到了一个分段错误。但是在我将变量名改为step2之后,它就可以工作了。
版本: swig 4.0.0 python 3.6.7
这会得到一个分段错误:
1.ex.cpp
#include<iostream>
int step = 0;
void test(){
step += 1;
printf("ok\n");
}2.ex.i
%module ex
%inline %{
extern void test();
%}3.run
swig -c++ -python ex.i
g++ -fPIC -c ex.cpp -c ex_wrap.cxx -I/home/lzhang/venv/include/python3.6m
g++ -shared ex.o ex_wrap.o -o _ex.so4.获取分段错误
$ python
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import ex
>>> ex.test()
Segmentation fault (core dumped)但我只更改了变量名:
#include<iostream>
int step2 = 0;
void test(){
step2 += 1;
printf("ok\n");
}重新编译后,它就可以工作了。
$ python
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import ex
>>> ex.test()
ok
>>> 怎样才能避免这种错误呢?
发布于 2019-06-24 15:58:05
问题的根源似乎在于step是从libc导出的,至少在一些常见的系统上是这样,所以您得到了一个全局名称空间冲突。
nm -D /lib/arm-linux-gnueabihf/libc-2.28.so|grep step
000c5210 W step(它是一个函数,我对它的用途有点好奇,因为我不熟悉它--原来它与正则表达式处理和在字符串缓冲区中查找已编译的正则表达式的下一个匹配项有关)
在您的特定示例中,最简单的解决方案是将全局变量step设置为static (或使用匿名名称空间):
#include<iostream>
static int step = 0;
void test(){
step += 1;
printf("ok\n");
}这足以修复您的示例。
最好确保所有全局变量都是静态的,除非你真的想要导出它们,特别是在构建共享对象(例如Python模块)时。
您还可以使用gcc的-fvisibility=hidden默认隐藏而不是导出全局变量。(SWIG确保需要导出的内容即使在设置此选项时仍可见)。
https://stackoverflow.com/questions/56707291
复制相似问题