0

我正在尝试使用此处找到的 xtensor-python 示例。

我安装了 xtensor-python、pybind11 和 xtensor,还创建了一个 CMakeLists.txt。

从 /build 我跑了。$ cmake .. $ 制作

它构建没有错误。

我的 CMakeLists.txt 看起来像这样。

cmake_minimum_required(VERSION 3.15)
project(P3)

find_package(xtensor-python REQUIRED)
find_package(pybind11 REQUIRED)
find_package(xtensor REQUIRED)

我的 example.cpp 文件。

#include <numeric>                        // Standard library import for std::accumulate
#include "pybind11/pybind11.h"            // Pybind11 import to define Python bindings
#include "xtensor/xmath.hpp"              // xtensor import for the C++ universal functions
#define FORCE_IMPORT_ARRAY                // numpy C api loading
#include "xtensor-python/pyarray.hpp"     // Numpy bindings

double sum_of_sines(xt::pyarray<double>& m)
{
    auto sines = xt::sin(m);  // sines does not actually hold values.
    return std::accumulate(sines.cbegin(), sines.cend(), 0.0);
}

PYBIND11_MODULE(ex3, m)
{
    xt::import_numpy();
    m.doc() = "Test module for xtensor python bindings";

    m.def("sum_of_sines", sum_of_sines, "Sum the sines of the input values");
}

我的python文件。

import numpy as np
import example as ext

a = np.arange(15).reshape(3, 5)
s = ext.sum_of_sines(v)
s

但是我的 python 文件无法导入我的 example.cpp 文件。

  File "examplepyth.py", line 2, in <module>
    import example as ext
ImportError: No module named 'example'

我是cmake的新手。我想知道如何使用 CMakeLists.txt 正确设置这个项目

4

2 回答 2

0

推荐的方法是使用 setup.py 文件而不是 cmake 来构建和安装。您可以使用cookie-cutter来获取为您生成的样板。

于 2019-08-22T14:03:38.133 回答
0

嘿,我不确定 xtensor-python,因为我没有使用它,但我可能会给你一些在 Anaconda 环境中使用 cmake 构建 pybind11 的指示。您的 Cmake.txt 看起来有点不完整。对我来说,以下设置有效:

在我的 Anaconda-shell 中,我使用以下命令:

cmake -S <folder where Cmake.txt is> B <folder where Cmake.txt is\build> -G"Visual Studio 15 2017 Win64" 

它将所有链接放入子文件夹构建中,因此可以通过以下方式完成实际构建

cmake --build build

必要的 Cmake.txt 如下所示。创建的库 TEST 然后位于子文件夹 debug\Build

#minimum version of cmake
cmake_minimum_required(VERSION 2.8.12)
#setup project
project(TEST)

#load the libraries
find_package(pybind11 REQUIRED)
set(EXTERNAL_LIBRARIES_ROOT_PATH  <Filepath where my external libraries are at>)
set(EIGEN3_INCLUDE_DIR ${EXTERNAL_LIBRARIES_ROOT_PATH}/eigen-eigen-c753b80c5aa6) 

#get all the files in the folder
file(GLOB SOURCES
    ${CMAKE_CURRENT_SOURCE_DIR}/*.h
    ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp   
)
#include the directories
include_directories(${PYTHON_INCLUDE_DIRS} ${pybind11_INCLUDE_DIRS} ${EIGEN3_INCLUDE_DIR})

pybind11_add_module(TEST MODULE ${SOURCES})

#in some cases need to link the libraries 
#target_link_libraries(TEST PUBLIC ${OpenCV_LIBRARIES} ${Boost_LIBRARIES})  

如果你想要一个我使用这个 Cmake.txt 文件的最小工作示例,它恰好是我在 stackoverflow 上发布的另一个问题:pybind11 how to use custom type caster for simple example class

希望这有助于作为第一个起点(我将 EIGEN3 留在里面,以便让您了解它是如何使用仅标头库完成的。对于像 OpenCV 这样的实际库,您还需要 target_link_libraries 命令)。

于 2019-08-23T18:14:18.463 回答