使用pybind11时无法导入numpy

问题描述

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

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

解决方法

使用有问题的代码编写pyfile.py。 使用以下代码编写main.cpp

node_modules

使用以下代码编写CMakeLists.txt

#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");
}

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