Pytorch 学习(9):Python C 扩展( C、C++代码-----C so 代码库------python代码调用)

 Pytorch 学习(9):Python C 扩展

 C、C++代码------>C so 代码库------->python代码调用

  •  VC 6.0 ++ 不建议使用,推荐使用cLion 集成开发环境。
  •  MinGW安装部署:windows 10 64 位,需安装mingw-w64版本(本地目录:G:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin),网络下载地址(https://sourceforge.net/projects/mingw-w64/)如果直接使用MinGW版本(本地目录:G:\MinGW\bin),MinGW编译的32位文件在windows 10 下运行报错:
runfile('D:/vcProjects2018/clion/python_c.py', wdir='D:/vcProjects2018/clion')
Traceback (most recent call last):

  File "", line 1, in 
    runfile('D:/vcProjects2018/clion/python_c.py', wdir='D:/vcProjects2018/clion')

  File "G:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
    execfile(filename, namespace)

  File "G:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "D:/vcProjects2018/clion/python_c.py", line 6, in 
    adder = CDLL('./adder.so')

  File "G:\ProgramData\Anaconda3\lib\ctypes\__init__.py", line 348, in __init__
    self._handle = _dlopen(self._name, mode)

OSError: [WinError 193] %1 不是有效的 Win32 应用程序。
  •  clion集成开发环境中新建一个add.c文件:

//sample C file to add 2 numbers - int and floats

#include 

int add_int(int, int);
float add_float(float, float);

int add_int(int num1, int num2){
    return num1 + num2;
}

float add_float(float num1, float num2){
    return num1 + num2;
}

使用gcc 进行编译:

D:\vcProjects2018\clion>gcc -shared -Wl,-soname,adder -o adder.so -fPIC add.c

Pytorch 学习(9):Python C 扩展( C、C++代码-----C so 代码库------python代码调用)_第1张图片

在python中调用编译以后的c文件

# -*- coding: utf-8 -*-

from ctypes import *

#load the shared object file
adder = CDLL('./adder.so')

#Find sum of integers
res_int = adder.add_int(4,5)
print ("Sum of 4 and 5 = " + str(res_int))

#Find sum of floats
a = c_float(5.5)
b = c_float(4.1)

add_float = adder.add_float
add_float.restype = c_float
print ("Sum of 5.5 and 4.1 = ", str(add_float(a, b)))

python运行结果如下:

runfile('D:/vcProjects2018/clion/python_c.py', wdir='D:/vcProjects2018/clion')
Sum of 4 and 5 = 9
Sum of 5.5 and 4.1 =  9.600000381469727

Pytorch 学习(9):Python C 扩展( C、C++代码-----C so 代码库------python代码调用)_第2张图片

 

你可能感兴趣的:(AI,&,Big,Data案例实战课程)