1

当我尝试使用 pybind11 将此文件嵌入 C++ 时,python3 文件中的“import numpy”语句会生成错误。以下python文件中除了“import numpy”和“import tensorflow”的其他语句(导入系统库)都可以成功执行

import tensorflow as tf
import numpy as np    

import sys
print('sys.version: ', sys.version)    
import os
print('os.getcwd: ', os.getcwd())    
import platform
print('platform: ', platform.platform())    
import time
print("Python time: ", time.time());

def create_vector(a,b):
    my_list = [ 0.1, 0.2, 0.3 ]
    return my_list

我收到以下错误

Segmentation fault (core dumped)

我可以从独立的 python 文件或 shell 成功导入和使用 numpy(见下文)

Python 3.6.8 (default, Apr  2 2020, 13:34:55) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> print(np.__version__)
1.18.5
4

1 回答 1

0

使用相关代码编写 pyfile.py。使用以下代码编写 main.cpp

#include <iostream>
#include "pybind11/embed.h"
namespace py = pybind11;
using namespace std;

int main()
{
    py::scoped_interpreter guard{};

    auto py_module = py::module::import("pyfile");
}

使用以下代码编写 CMakeLists.txt

set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
project(project) # project name
include_directories (/usr/include/python3.6m)# set accordingly
find_package(pybind11 REQUIRED)
add_executable(project main.cpp)
target_link_libraries (project pybind11::embed)# keep bybind11 dir along with main.cpp

正确链接 pyfile 或将其保存在构建目录中。在构建之前删除 CMakeCache.txt(cmake .. 和 make)

于 2020-12-07T11:41:21.813 回答