登录
首页 >  Golang >  Go问答

Golang SWIG演示2:切片越界引发恐慌

来源:stackoverflow

时间:2024-03-20 14:57:31 173浏览 收藏

在使用 SWIG Go 示例中的“常量”示例时,如果使用 -intgosize 32 作为 SWIG 调用的参数,会出现切片超出范围的恐慌。原因是 sconst2 字符串在使用 -intgosize 32 时会导致恐慌,而 sconst 字符串不会。这与 Go 中 int 的大小有关,因为 int32 变量的范围为 -2147483648 到 2147483647,而 sconst2 的长度超过了这个范围,因此引发了恐慌。要解决此问题,应使用 int64 变量,其范围更广。

问题内容

我目前正在研究 swig go 示例,但我在第二个示例“常量”上遇到问题

出于某种原因,我会出现切片超出范围的恐慌,但前提是我在 swig 调用中指定 32 作为 -intgosize 参数的参数。

如果我使用 swig -go -intgosize 64 example.i 运行 swig,一切正常

example.i swig 文件如下所示

/* file : example.i */
%module example

/* a few preprocessor macros */

#define    iconst      42
#define    fconst      2.1828
#define    cconst      'x'
#define    cconst2     '\n'
#define    sconst      "hello world"
#define    sconst2     "\"hello world\""

/* this should work just fine */
#define    expr        iconst + 3*(fconst)

/* this shouldn't do anything */
#define    extern      extern

/* neither should this (bar isn't defined) */
#define    foo         (iconst + bar)

/* the following directives also produce constants */

%constant int iconst = 37;
%constant double fconst = 3.14;

从使用 32 参数运行 swig 时得到的输出来看,我认为恐慌是由 sconst2 引起的,在注释掉 #define sconst2 行后,恐慌消失了。

sconst2 的输出如下所示:

panic: runtime error: slice bounds out of range [:824633720845] with length 2147483647

goroutine 1 [running]:
swigtest/02_constants.swigCopyString(0x1056760, 0xc00000000d, 0xc000107ef0, 0xc000107ef8)
        C:/Users/visfgp/go/personal_code/src/swigtest/02_constants/example.go:64 +0xb0
swigtest/02_constants._swig_getSCONST2(0x50230a, 0xc00003e1e0)
        C:/Users/visfgp/go/personal_code/src/swigtest/02_constants/example.go:97 +0x4a
swigtest/02_constants.init()
        C:/Users/visfgp/go/personal_code/src/swigtest/02_constants/example.go:101 +0x38

我的问题是这个字符串特别引发了这种恐慌,为什么它不是由 sconst 字符串引发的,它与 go int 的大小有什么关系?


解决方案


定义 int32 变量时,其范围为 -21474836482147483647。也许您的变量超出了 [:824633720845] 这个范围。在这种情况下你应该使用 int64!

理论要掌握,实操不能落!以上关于《Golang SWIG演示2:切片越界引发恐慌》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>