我如何在 SWIG 中包装 C 库,通常在 C 编译期间链接它?

How can I wrap a C-Library in SWIG, which has usually to be linked during C-compilation?

给定一个 C 库,如果我想使用它的功能,必须在编译期间链接它。我想使用 SWIG 在 Python 中访问这些函数。我只能找到使用 SWIG 包装 C 代码 (example.c) 的示例和介绍,没有找到如何包装动态库 (example.so) 的方法。

要使 .so(或 .a)库案例正常工作,您需要做的就是在执行示例构建过程的编译步骤时适当地 link 库。您仍然需要编译生成的 example_wrap.c,这是您可以 link 对抗事物的地方。

根据 SWIG 文档修改为:

$ swig -python example.i
$ gcc -O2 -fPIC -c example.c
$ gcc -O2 -fPIC -c example_wrap.c -I/usr/local/include/python2.5
$ gcc -shared example_wrap.o -o _example.so -lmylib.so

实际上你也可以在编译时跳过这个 linker 步骤并在运行时使用 dlopen 而不是通过注入一些额外的代码到模块的 Python 部分在加载来自 SWIG 的共享对象之前调用 dlopen。