tangqi_334
tangqi_334
采纳率0%
2019-08-19 11:56 阅读 1.2k

linux使用clion进行c++和python的交叉编译,无法导入python的第三方库

在ubuntu14.04下使用clion进行c++调用python编写的模块,当python中import第三方库(如numpy时),出现错误。具体如下:

这是我的代码:
cmakelist:

cmake_minimum_required(VERSION 3.5)
project(image_pretreat)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -util -ldl -pthread")


# 添加Python.h头文件路径
include_directories(/home/neil/.pyenv/versions/3.6.4/include/python3.6m)

# 添加python动态链接库文件目录
link_directories(/home/neil/.pyenv/versions/3.6.4/lib/python3.6/config-3.6m-x86_64-linux-gnu)

set(SOURCE_FILES main.cpp)
add_executable(image_pretreat ${SOURCE_FILES})

# 依赖库文件
target_link_libraries(image_pretreat libpython3.6m.a)
target_link_libraries(image_pretreat ${CMAKE_DL_LIBS})
target_link_libraries(image_pretreat util)

main函数

#include <Python.h>
#include <iostream>
using namespace std;

int main()
{
    Py_Initialize();

    //声明python对象(模型、函数、参数、返回值)
    PyObject *pModule, *pFunction, *pArgs, *pRetValue;
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('/home/neil/ClionProjects/image_pretreat')");

    //调用python模块
    pModule = PyImport_ImportModule("test123");

    if (!pModule)
    {
        printf("import python failed!!\n");
        return -1;
    }

    //调用python模块中的函数
    pFunction = PyObject_GetAttrString(pModule, "add");
    if (!pFunction)
    {
        printf("get python function failed!!!\n");
        return -1;
    }

    //新建python元组对象
    pArgs = PyTuple_New(2);
    PyTuple_SetItem(pArgs, 0, Py_BuildValue("i", 1));
    PyTuple_SetItem(pArgs, 1, Py_BuildValue("i", 2));

    int r1,r2;
    r1=r2=0;
    pRetValue=PyObject_CallObject(pFunction, pArgs);
    PyArg_ParseTuple(pRetValue, "i|i", &r1, &r2);
    printf("%d,%d",r1,r2);

    //关闭 Python 脚本解释器
    Py_Finalize();
    return 0;
}

Python模块

import numpy as np
def add(a,b):
    return a+b,a-b

报错:
import python failed!!
Process finished with exit code 255

已采取方法:
1、将python3.6各个路径都包含进了PYTHONPATH和PYTHONHOME环境变量
2、主函数中手动设置py_SetPythonhome函数

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

相关推荐