【问题标题】:Wrap C++ to Python - where parts of the code is a shared library without source将 C++ 包装到 Python - 其中部分代码是没有源代码的共享库
【发布时间】:2023-03-24 23:17:01
【问题描述】:

我有一个带有头文件的 Linux .so-library secdyn.so,但没有源代码。

/* secdyn.h */
int sec2(int a);

我想通过 Swig 将它包装到 Python 中,因此我编写了一个 subdyn.h

#include <iostream>
#include "secdyn.h"
int subdyn(int a,int debuglevel);

还有一个 subdyn.cpp

#include "subdyn.h"
int subdyn(int a,int debuglevel)
{
  if (debuglevel>0) std::cout << "a = " << a << std::endl;
  return sec2(a);
}

还有一个 subdyn.i(见下文我的回答!!!-第一行有错误)

%module substatic
%{ 
  #define SWIG_FILE_WITH_INIT
  #include "subdyn.h"
%}
%include "subdyn.h"

并编译

swig -c++ -python subdyn.i
g++ -fPIC subdyn_wrap.cxx -c -g -I/usr/include/python2.7/
g++ -fPIC subdyn.cpp -c -g
g++ -shared subdyn_wrap.o subdyn.o secdyn.so -o _subdyn.so 

这个构建并且我设置 $LD_LIBRARY_PATH 以包含“pwd”

$ ldd _subdyn.so
linux-gate.so.1 =>  (0xb7702000)
secdyn.so => ./secdyn.so (0xb76f4000)
libstdc++.so.6 => /usr/lib/i386-linux-gnu/libstdc++.so.6 (0xb75ee000)
libm.so.6 => /lib/i386-linux-gnu/i686/cmov/libm.so.6 (0xb75c7000)
libgcc_s.so.1 => /lib/i386-linux-gnu/libgcc_s.so.1 (0xb75aa000)
libc.so.6 => /lib/i386-linux-gnu/i686/cmov/libc.so.6 (0xb7446000)
/lib/ld-linux.so.2 (0xb7703000)

我可以制作一个使用 secdyn.so 和 subdyn.so 的 C++ 二进制文件——效果很好。

但是我无法将此库导入 Python

$ python
>>> import subdyn
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: dynamic module does not define init function (initsubdyn)

我可以注意到,如果 secdyn 作为静态库提供,一切正常,但对于动态库,这会中断。

我附上了一个有效的静态 swig 链接示例,以及一个在 http://petertoft.dk/code/swig.tgz 不起作用的动态链接示例(上面的代码)

线索?

【问题讨论】:

  • 你必须导出符号。
  • 我该怎么做?感谢卡罗利
  • 我认为您的帖子中有错字:ldd subdyn.so 应该是ldd _subdyn.so? +1 寻找解决方案和发布!
  • 很好看的 Scholli - 上面更新

标签: python c++ linux swig


【解决方案1】:

我在上面遗漏的错误是错误的 subdyn.i。第一行应该是 %module subdyn

然后就可以了。我重新上传了http://petertoft.dk/code/swig.tgz - 其中包含一个静态和一个动态示例。两者现在都可以工作:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-01
    • 2019-03-25
    • 2016-01-28
    • 2018-08-22
    • 1970-01-01
    • 2020-07-03
    • 2011-03-16
    • 2016-11-13
    相关资源
    最近更新 更多