使用SWIG实现C++和Lua时出现了Abort trap错误。

我最近第一次使用SWIG创建C++的新Lua模块。我使用Mac OS(El Capitan)进行开发。让我一步一步地解释我所做的事情:

1)创建.cpp文件

int myAddition(int x, int y)
{
  return (x+y);
}

int mySubtraction(int x, int y)
{
  return (x-y);
}

2)创建接口文件(.i):

%module test
%{
   extern int myAddition(int x, int y);
   extern int mySubtraction(int x, int y);
%}
 extern int myAddition(int x, int y);
 extern int mySubtraction(int x, int y);

3)使用以下命令创建包装器和共享库:

 swig -c++ -lua test.i
 g++ -I/usr/local/include -c test_wrap.cxx -o test_wrap.o
 g++ -c test.cpp -o test.o
 g++ -bundle -L/usr/local/lib/ -llua test_wrap.o test.o -o test.so

4)创建.lua文件以测试新模块:

require("test")
print(test.myAddition(10,40))
print(test.mySubtraction(20,40))

脚本的输出如下:

50.0 -20.0 lua(21360,0x7fff7b739000)malloc:\*error for object 0x10d86b998:pointer being freed was not allocated *****set a breakpoint in malloc_error_break to debug Abort trap: 6

如果我将脚本更改为以下内容:

require("test")
print(test.myAddition(10,40))
print(test.mySubtraction(20,40))
os.exit()

这一切似乎都很好:

[输出] 50.0 -20.0

你发现了任何问题,或者需要在脚本完成后调用os.exit()吗?

编辑:Lua版本为5.3.2。_g++ -Wl--verbose-bundle -I/usr/local/include/ -L/usr/local/lib/ -llua test_wrap.o test.o -o test.so_的输出如下:

Apple LLVM版本7.0.2(clang-700.1.81) 目标:x86_64-apple-darwin15.3.0 线程模型:posix “/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld”-demangle-dynamic-arch x86_64-bundle-macosx_version_min 10.11.0-syslibroot/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk -o test.so -L/usr/local/lib/ -llua test_wrap.o test.o-lc ++ -lSystem /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/..。/lib/clang/7.0.2/lib/darwin/libclang_rt.osx.a

点赞