将c++打包到Python中——在Python中,代码的一部分是没有源代码的共享库

时间:2021-04-26 21:23:31

I have a Linux .so-library secdyn.so with a headerfile without source.

我有一个Linux .so-library secdyn。所以有一个没有源代码的headerfile。

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

I want to wrap this to Python via Swig, thus I write a subdyn.h

我想通过Swig将其封装到Python中,因此我要编写一个subdyn.h

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

and a subdyn.cpp

和一个subdyn.cpp

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

and a subdyn.i (see below in my answer!!! - error in this first line)

和一个subdyn。我(见下面的答案!!!)-第一行错误

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

and compile with

和编译

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 

This builds and I set $LD_LIBRARY_PATH to include "pwd"

我设置了$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)

I can make a C++ binary that uses secdyn.so and subdyn.so - that works fine.

我可以用secdyn生成一个c++二进制。所以,subdyn。这很好。

However I cannot import this library to Python

但是,我不能将这个库导入Python。

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

I can note that everything works fine if the secdyn comes as a static libary, but for a dynamic library this breaks.

我可以注意到,如果secdyn以静态libary的形式出现,那么一切都可以正常工作,但对于动态库,这就会中断。

I have attached a static swig link exampe that works, and a dynamic link example (the code above) which does not work at http://petertoft.dk/code/swig.tgz

我附加了一个静态swig link exampe,以及一个动态链接示例(上面的代码),它在http://petertoft.dk/code/swig.tgz上不能工作

Clues?

线索吗?

1 个解决方案

#1


2  

The bug I missed above is the subdyn.i which was wrong. The first line should read %module subdyn

我错过的bug是subdyn。我哪错了。第一行应该读取%模块subdyn

Then it works. I have re-uploaded http://petertoft.dk/code/swig.tgz - which contains a static and a dynamic example. Both work now :)

它的工作原理。我已经上传完毕http://petertoft.dk/code/swig。tgz -包含静态和动态示例。现在工作:)

#1


2  

The bug I missed above is the subdyn.i which was wrong. The first line should read %module subdyn

我错过的bug是subdyn。我哪错了。第一行应该读取%模块subdyn

Then it works. I have re-uploaded http://petertoft.dk/code/swig.tgz - which contains a static and a dynamic example. Both work now :)

它的工作原理。我已经上传完毕http://petertoft.dk/code/swig。tgz -包含静态和动态示例。现在工作:)