一、环境安装
1. 安装C、C++编译器
Linux安装gcc和g++(C++)的库
两个工具需要进入命令行输入命令,按下ctrl + alt + T ,进入命令行,依次输入下列命令(每次命令输入完需要回车确认,当过程中出现确认是否安装的信息,Y/N这种,输入Y,并回车确认):
(0) 先检查是否安装:
which gcc(查看gcc安装位置)
gcc -v(查看版本)
(1)sudo add-apt-repository ppa:ubuntu-toolchain-r/test
(2)sudo apt-get update
(3)sudo apt-get install gcc
(4)sudo apt-get install g++
2. 安装python、pip3
一般Ubuntu 18.04会自带Python3,但是在命令行Python不能访问,这时要创建软连接。
创建软连接,先查看python3.6.4的安装路径:
which python3
# /usr/bin/python3
cd /usr/bin
sudo ln -s /usr/bin/python3 python
pip3安装命令:
sudo apt install python3-pip
验证pip3安装:
pip3 --version
# pip 9.0.1 from /usr/lib/python3/dist-packages (python 3.6)
安装开发工具,对于Python 3:
sudo apt install build-essential python3-dev python3-setuptools
3. 安装cython
对于python3:
安装命令:
sudo pip3 install cython
验证安装:
which cython
# /usr/local/bin/cythonn
cython --version
# Cython version 0.29.21
4. 安装Jupyter
安装命令:
sudo pip install jupyter
运行Jupyter:
jupyter notebook
二、代码
1. 代码
get_angle.h
float _get_angle(float x, float y);
get_angle.c
#include "get_angle.h"
#include <math.h>
#define pi (2*acos(0.0))
// 方向向量转化为角度
float _get_angle(float x, float y){
float angle = 123;
if(y == 0){
if(x < 0)
angle = 180;
else
angle = 0;
}
if(x == 0){
if(y > 0)
angle = 90;
else
angle = 270;
}
else{
float tan_yx = fabs(y)/fabs(x);
if (y > 0 && x < 0){
angle = 180 - atan(tan_yx)*180/pi; //90-180
}else if(y > 0 && x > 0){
angle = atan(tan_yx)*180 / pi; //0-90
}else if (y < 0 && x < 0){
angle = 180 + atan(tan_yx)*180/pi; //180-270
}else if (y < 0 && x > 0){
angle = 360- atan(tan_yx)*180/pi; //270-360
}
}
return angle;
}
get_angle_c.pyx
cdef extern from "get_angle.h":
float _get_angle(float x, float y)
def get_angle(float x, float y):
return _get_angle(x, y)
setup_c.py
from distutils.core import setup, Extension
from Cython.Build import cythonize
import numpy
setup(ext_modules = cythonize(Extension(
'get_angle_c',
sources=['get_angle_c.pyx', 'get_angle.c'],
language='c',
# include_dirs=[numpy.get_include()],
library_dirs=[],
# libraries=["method"],
extra_compile_args=[],
extra_link_args=[]
)))
命令行
python setup_c.py build_ext --inplace
编译产生get_angle_c.c
和get_angle_c.pyd
(windows)或get_angle_c.so
(linux)文件。
引用时import get_angle_c
即可。