将 SWIG 用于依赖于另一个 .cpp 的 .cpp

Use SWIG for .cpp which depends on another .cpp

我有一个 .cpp 文件调用另一个 .cpp 文件。我想使用 SWIG 为此创建一个 Python 包装器。 我如何使用 SWIG 制作它。 当我只有一个 .cpp 文件时,我可以通过以下方式创建一个 .so:

//app.cpp
#include "app.hpp"
int p(int a)
{
std::cout<<"hello...SWIG runs fine!"<<std::endl;
return a;
}


//app.hpp
#include <iostream>
int p(int a);


//app.i
%module app
%{
#include "app.hpp"
%}
%include "app.hpp"

命令 运行 是:

我用这个方法生成.so文件成功了。但是,现在我的 app.cpp 需要使用另一个 .cpp 文件中定义的函数 (hello.cpp 中名为 int fn1(int x) 的函数)。我现在如何生成 .so?如果有人能提供一个小例子,那就太好了!

编辑::有人建议我必须同时使用 SWIG 和 CMAKE。这是真的?如果是,我该怎么做?

解决了!

swig -c++ -python file1.i

g++ -Isrc -fPIC -I/../../../../usr/include/python3.6m -I/../../../../usr/include/x86_64-linux-gnu/python3.6m -lpython3.6m -c file1.cpp file2.cpp file1_wrap.cxx

g++ -shared -fPIC -o _file1.pyd file1.o file2.o file1_wrap.o

事实证明我们可以使用 CMake 来定义依赖项并自动执行此过程。 此外,如 SWIG 文档 Introduction_build_system

中所述,SWIG 可以与 CMake 一起使用