Kia*_*Lin 5 c python dll cython python-3.x
我有一个 C 文件,它用 Cython 调用 Python 函数。
Python文件有import torch(Pytorch 0.4.0),函数使用torch。
然后我用这个 C 文件创建 .dll。
问题发生在这里:
当我在cpp文件中使用这个dll时,它有ModuleNotFoundError。
这是我的简单代码:
环境: Windows 10 x64 视觉工作室 2017 蟒蛇3 Python 3.6 火炬0.4.0 赛通0.28.2
PyTest.pyx
import torch
cdef public void HelloWorld():
print('Hello!')
print(torch.__version__)
print('World!')
Run Code Online (Sandbox Code Playgroud)
安装程序.py
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
from Cython.Build import cythonize
setup(name = 'PyTest',
cmdclass = {'build_ext' : build_ext},
ext_modules = cythonize('PyTest.pyx')
)
Run Code Online (Sandbox Code Playgroud)
在终端中运行 setup.py
python setup.py build_ext --inplace
Run Code Online (Sandbox Code Playgroud)
生成文件:PyTest.c 和 PyTest.h
创建 C 文件:C_Test.c 和 C_Test.h
C_测试.h
#include <Python.h>
#include "PyTest.h"
#include <stdio.h>
#ifdef __cplusplus
extern "C" {
#endif
__declspec(dllexport) int testdll();
#ifdef __cplusplus
}
#endif
Run Code Online (Sandbox Code Playgroud)
C_测试.c
#include "C_Test.h"
int testdll()
{
Py_Initialize();
if(Py_IsInitialized())
printf("Py_Initialize Done!\n");
if(!PyInit_PyTest())
printf("PyInit_PyTest Fail!\n");
HelloWorld();
Py_Finalize();
getchar();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
2017 年开发者命令提示符:
cd "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC"
vcvarsall amd64
cd "{my C files path}"
cl /LD C_Test.c PyTest.c -I C:\Anaconda3\envs\Pytorch\include C:\Anaconda3\envs\Pytorch\libs\python36.lib
Run Code Online (Sandbox Code Playgroud)
生成C_Test.dll、C_Test.lib、C_Test.exp、C_Test.obj
然后使用 Visual Studio 2017 创建 c++ 项目,并执行一些操作以确保它可以读取 C_Test.dll
Cpp测试.cpp
#include "stdafx.h"
#include "Python.h"
#include "C_Test.h"
int main()
{
testdll();
getchar();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是我的程序执行的结果:
Py_Initialize Done!
PyInit_PyTest Fail!
Traceback (most recent call last):
File "PyTest.pyx", line 2, in init PyTest
ModuleNotFoundError: No module named 'torch'
The above exception was the direct cause of the following exception:
SystemError: <built-in method write of _io.TextIOWrapper object at 0x000002C2091877E0> returned a result with an error set
Exception ignored in: 'PyTest.HelloWorld'
SystemError: <built-in method write of _io.TextIOWrapper object at 0x000002C2091877E0> returned a result with an error set
Hello!
Run Code Online (Sandbox Code Playgroud)