Pytorch 学习(9):Python C 扩展
C、C++代码------>C so 代码库------->python代码调用
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 应用程序。
//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
在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