我的setup.py中的代码是这样写的:from distutils.core import setup from distutils.extension import Extension import Cython from Cython.Build import cythonize import numpy extensions = [ Extension('models.model', ['model.pyx'], include_dirs=[numpy.get_include()],language="c++"), ] setup( name='models', ext_modules=cythonize(extensions), ) # 添加以下两行代码 for e in extensions: e.cython_directives = {"language_level": 3} ext_modules = cythonize(extensions),但是当我运行python setup.py build_ext --inplace命令时,却只生成了cpp文件,没有hpp文件,我希望生成hpp和cpp应该怎么做
时间: 2024-01-17 12:02:51 浏览: 108
通常,Cython会自动生成C++的头文件(.hpp)并将其包含在生成的C++文件中。如果您的Cython文件中包含C++头文件,则必须手动指定这些头文件。为此,您可以使用Cython的include语句。
在您的Cython文件中,添加以下代码:
```python
# distutils: language = c++
# distutils: include_dirs = /path/to/header/files
cdef extern from "/path/to/header/files/your_header_file.hpp":
# your function declarations
```
请确保将路径替换为实际的头文件路径。然后,在您的setup.py文件中,将include_dirs参数设置为包含您的头文件的目录,如下所示:
```python
extensions = [
Extension('models.model', ['model.pyx'], include_dirs=['/path/to/header/files'], language="c++"),
]
```
最后,运行python setup.py build_ext --inplace命令以在当前目录中生成hpp和cpp文件。
相关问题
我用Cython封装了一个来自segment-anything-master项目里的.pth模型,我的.pyx文件是这么写的import sys import numpy as np import matplotlib import matplotlib.pyplot as plt import cv2 from typing import Any, Dict, List, Optional, Tuple sys.path.append("/app/PythonProjects/segment-anything-main") from segment_anything import sam_model_registry, SamAutomaticMaskGenerator, SamPredictor # model.pyxcdef class SamModel: def __init__(self, str model_type,str sam_checkpoint, str device = "cpu", points_per_side: Optional[int] = 32, points_per_batch: int = 64, point_grids: Optional[List[np.ndarray]] = None): self.sam = sam_model_registry[model_type](checkpoint=sam_checkpoint) self.sam.to(device) self.mask_generator = SamAutomaticMaskGenerator(self.sam,points_per_side = points_per_side, points_per_batch = points_per_batch, point_grids = point_grids) def __getmodel__(self): return self.sam def __callmodel__( self, input: np.array ): masks = self.mask_generator.generate(input) return masks,我的setup.py文件是这样写的:from distutils.core import setup from distutils.extension import Extension import Cython from Cython.Build import cythonize import numpy extensions = [ Extension('models.model', ['/app/PythonProjects/segment-anything-main/SamCython/models/model.pyx'], include_dirs=[numpy.get_include()]), ] setup( name='models', ext_modules=cythonize(extensions), ),给我一篇C++调动这个模型的实例
好的,以下是一个简单的C++调用这个模型的示例代码:
```cpp
#include <Python.h>
#include <numpy/arrayobject.h>
#include <iostream>
int main()
{
// 初始化 Python 解释器
Py_Initialize();
// 加载 NumPy 模块
import_array();
// 加载 Python 模块和函数
PyObject* pModule = PyImport_ImportModule("models.model");
if (!pModule) {
std::cerr << "Failed to import module" << std::endl;
return 1;
}
PyObject* pFunc = PyObject_GetAttrString(pModule, "__callmodel__");
if (!pFunc || !PyCallable_Check(pFunc)) {
std::cerr << "Failed to get function" << std::endl;
return 1;
}
// 准备输入数据
int width = 640;
int height = 480;
npy_intp dims[3] = { height, width, 3 };
unsigned char* inputData = new unsigned char[width * height * 3];
// 填充 inputData 数据
// 创建 NumPy 数组
PyObject* pInputArray = PyArray_SimpleNewFromData(
3, dims, NPY_UINT8, inputData);
// 调用函数
PyObject* pOutputArray = PyObject_CallFunction(pFunc, "O", pInputArray);
if (!pOutputArray) {
std::cerr << "Failed to call function" << std::endl;
return 1;
}
// 获取输出数据
unsigned char* outputData = PyArray_DATA((PyArrayObject*)pOutputArray);
// 处理 outputData 数据
// 释放资源
Py_DECREF(pInputArray);
Py_DECREF(pOutputArray);
Py_DECREF(pFunc);
Py_DECREF(pModule);
Py_Finalize();
delete[] inputData;
return 0;
}
```
需要注意的是,在编译时,需要链接 Python 和 NumPy 库。可以使用以下命令进行编译:
```
g++ -o main main.cpp -I/usr/include/python3.8 -lpython3.8 -lpython3 -lm -ldl -I/usr/local/lib/python3.8/dist-packages/numpy/core/include -L/usr/local/lib/python3.8/config-3.8-x86_64-linux-gnu -lpython3.8 -lcrypt -lpthread -ldl -lutil -lm -Wno-unused-result
```
其中,`-I` 参数指定 Python 和 NumPy 的头文件路径,`-l` 参数指定 Python 的库文件和 NumPy 的库文件(需要根据自己的 Python 版本和安装路径进行调整)。
Building wheels for collected packages: cython_bbox Building wheel for cython_bbox (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [5 lines of output] running bdist_wheel running build running build_ext building 'cython_bbox' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for cython_bbox Running setup.py clean for cython_bbox Failed to build cython_bbox Installing collected packages: cython_bbox Running setup.py install for cython_bbox ... error error: subprocess-exited-with-error × Running setup.py install for cython_bbox did not run successfully. │ exit code: 1 ╰─> [18 lines of output] running install D:\python\envs\yolov578\lib\site-packages\setuptools\_distutils\cmd.py:66: SetuptoolsDeprecationWarning: setup.py install is deprecated. !! ******************************************************************************** Please avoid running ``setup.py`` directly. Instead, use pypa/build, pypa/installer, pypa/build or other standards-based tools. See https://blog.ganssle.io/articles/2021/10/setup-py-deprecated.html for details. ******************************************************************************** !! self.initialize_options() running build running build_ext building 'cython_bbox' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: legacy-install-failure × Encountered error while trying to install package. ╰─> cython_bbox note: This is an issue with the package mentioned above, not pip. hint: See above for output from the failure.
这个错误提示是由于安装cython_bbox时缺少Microsoft Visual C++ 14.0或更高版本,你需要安装该工具才能成功构建cython_bbox。你可以通过以下链接下载并安装Microsoft C++ Build Tools:https://visualstudio.microsoft.com/visual-cpp-build-tools/。安装完成后,再次尝试安装cython_bbox即可。另外,提示中还提到了一些关于setup.py install的警告信息,建议使用其他标准工具来代替直接运行setup.py install。
阅读全文