[c++][python] swig的简单使用

1.写逻辑

1.1 编写要实现某功能的类(cpp)

编写要封装的类,最好接口都是简单的数据类型便于处理,要有独立的头文件

// myfunc.h
class Test()
{
public:
    Test();
    ~Test();
    void test();
};
// myfunc.cpp
#include "myfunc.h"
#include <iostream>
using namespace std;

Test::Test()
{}
Test::~Test()
{}

void Test::test()//测试函数。。。
{
    cout<<"test!"<<endl;
}

上面就是实现了某功能的cpp代码

1.2 搅和搅和
// main.cpp
#include<iostream>
#include<cstdio>
#include <Python.h>//include失败的话要加一下路径 3.1
#include "myfunc.h"
using namespace std;

int main()
{
    Test mc = Test();
    mc.test();
    return 0;
}
// build.sh
#!/bin/bash
g++ main.cpp myfunc.cpp myfunc.h -o main
//编译完成后 ./main 试一下会不会有输出

2 写接口文件

2.1 编写swig使用的接口文件

swig使用的文件以 .i 形式 结尾

// myfunc.i
%module myfunc
%{
#define SWIG_FILE_WITH_INIT
#include "myfunc.h"
%}
%include "myfunc.h"

编写好之后编译成动态链接库,这里直接去一个新的文件夹里生成文件了

#!/bin/bash

FILE="myfunc" #在这直接指定好模块的名字

rm swig_build -rf #在一个新的目录里生成文件
mkdir swig_build
cd swig_build

cp ../${FILE}.h . #把源文件复制来一份
cp ../${FILE}.cpp .
cp ../${FILE}.i .

# 编译c++文件 生成python版本的wrap
swig -c++ -python -outcurrentdir ${FILE}.i 

# 编译文件,生成动态链接库
g++ -fPIC -c ${FILE}.cpp
g++ -fPIC -c ${FILE}_wrap.cxx $(python-config --cflags)
g++ -shared ${FILE}.o ${FILE}_wrap.o $(python-config --ldflags) -o _${FILE}.so
#注意生成的动态链接库名字前面有'_'
2.2 搅和搅和
# demo.py
import sys
# 生成的动态链接库在那个目录里
sys.path.append("./swig_build/")

import myfunc 
c = myfunc.Test()
# 到这失败的 看看是不是前面的'myfunc'名字哪一步不对

c.test() #诶好使了

3 问题

3.1 #include <Python.h> 失败

这个要添加这个头文件的路径,有python运行环境的应该都会有这个文件

find / -name "Python.h"
找到文件的路径
(前方sudo警告)
/etc/profile 文件中添加这一行
export CPLUS_INCLUDE_PATH=$CPLUS_INCLUDE_PATH:找到的路径
source /etc/profile
参考https://blog.csdn.net/ztguang/article/details/51015839

还不行试试这个我没看
https://www.cnblogs.com/tlz888/p/9691548.html

3.2 编译好了调用时候报错 undefined symbol:__gxx_personality_v0

应该是 用gcc编译连接的c++
看看https://blog.csdn.net/guochangfei/article/details/81562144
https://www.cnblogs.com/zhangsir6/articles/2956798.html

3.3 datui

1.详细介绍 c++和python 在 swig 的转换
https://blog.csdn.net/xxxl/article/details/8288387
2.另一种高达上的生成动态链接库方式 python.distutils
https://blog.csdn.net/virusnono/article/details/77961701
https://blog.csdn.net/tiankongtiankong01/article/details/80420033

猜你喜欢

转载自blog.csdn.net/sszzyzzy/article/details/89945925
今日推荐