【发布时间】:2012-04-11 09:50:53
【问题描述】:
我已经将一个 C++ 程序编译成一个动态库,我现在通过 ctypes 在 python 中调用它。但是,我收到以下错误:
*** glibc detected *** ../../bin/python: free(): invalid pointer: 0x00007fbdf8ae3500 ***
我如何确定这是 C++ 代码中的错误,还是我使用 ctypes 的方式?
C++ 库在与 C 程序链接时成功运行,或者如果我将其编译为独立程序。当与 ctypes 结合使用时,它总是在 C++ 行崩溃:
// ... A bunch of code
if(tempBuffer) {
delete[] tempBuffer;
// More code below that never runs...
失败的 Python 代码:
def test(fileName):
feedbackLib = cdll.LoadLibrary("./libpitch.so")
# Set return type to a character pointer
feedbackLib.getPitchString.restype = c_char_p
feedbackLib.getPitchString.argtypes = [c_char_p]
# Crashes Here!
feedbackStr = feedbackLib.getPitchString(fileName)
return feedbackStr
出于某种原因,如果我像这样进行更改,我可以让 python 程序成功运行:
def test(fileName):
# I've only changed this line
feedbackLib = CDLL("./libpitch.so")
# Set return type to a character pointer
feedbackLib.getPitchString.restype = c_char_p
feedbackLib.getPitchString.argtypes = [c_char_p]
# No longer crashes!
feedbackStr = feedbackLib.getPitchString(fileName)
return feedbackStr
但是,如果我开始向上述函数添加东西(我需要这样做),它会给我其他 glibc 错误。
以下是有关我如何编译 C++ 的信息,以防相关。
我正在调用的函数的标头,使用 extern "C" 似乎是如何让 C++ 代码与 CTypes 一起工作:
extern "C" char* getPitchString(char* filename);
g++ 命令:
$(CXX) $(LDFLAGS) -fPIC -c $(SRCS) $(LIBS)
$(CXX) -shared -Wl,-soname,libpitch.so -o libpitch.so $(OBJS) $(LIBS)
【问题讨论】:
-
Python 代码看起来是正确的。为什么
getPitchString打电话给free? -
getPitchString 从 C++ 库中调用一堆代码。
标签: c++ python dynamic ctypes glibc