You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python调用Go编译的共享库出现pointer being freed was not allocated错误如何解决

报错原因
  • 核心问题是Python的ctypes默认将外部函数的返回值视为int类型:你Go侧TestString返回的是64位C字符指针,在64位操作系统下,int仅占32位,返回的指针地址会被强制截断为错误的地址值,把这个错误地址传给FreeCString执行内存释放操作时,系统就会抛出「指针未分配」的错误。
  • 次要问题:你的Go代码中使用了unsafe.Pointer但没有显式导入unsafe包,编译阶段就会报错,无法生成正确的共享库文件。
  • 额外隐患:你在执行FreeCString释放指针后还打印b,属于野指针访问,就算前面的问题解决也会出现异常。
解决步骤
  1. 先修正Go代码,补充导入unsafe包:
package main

// #include <stdio.h>
// #include <stdlib.h>
// #include <errno.h>
import "C"
import "unsafe"

//export FreeCString
func FreeCString(ptr *C.char) {
    C.free(unsafe.Pointer(ptr))
}

//export TestString
func TestString() *C.char {
    return C.CString("Hello World")
}

编译命令参考(macOS环境为例):go build -buildmode=c-shared -o test.so main.go

  1. 修正Python代码,显式指定TestString的返回值类型为c_char_p,并且调整操作顺序,在释放指针前读取字符串内容:
from ctypes import *
from ctypes import cdll

lib = cdll.LoadLibrary('./test.so')
# 显式声明返回值类型为C字符指针
lib.TestString.restype = c_char_p

b = lib.TestString()
# 释放指针前先读取内容
print(b.decode('utf-8'))
lib.FreeCString(b)

内容的提问来源于stack exchange,提问作者JJ Cauton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 20:36:05