如何从python脚本调用共享库(.so文件)?

2024-06-09 22:35:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个共享库hello_ext.so。我需要在python脚本中导入这个共享库。 目录是:

- project
| - py_binding
  | - hello_ext.cpp
  | - CMakeLists.txt
| - python_script.py
| - CMakeLists.txt

装订正确且有效

cmake ..make之后,可以从build文件夹调用库

$ python3
$ from hello_ext import greet
$ greet()
'hello, world'

因此,管道工程。 但是,如果我使用python3 /<path_to_sscript>/python_script.py运行python脚本 我得到这个错误

Traceback (most recent call last):
  File "/home/sharad/git_repository/longitudinal_control_pid/py_bindings/arduino_connection_usb.py", line 1, in <module>
    from hello_ext import greet
ModuleNotFoundError: No module named 'hello_ext'

我相信.so在python脚本中是不可见的。 我正在使用cmake作为项目

CMakeLists.txtpy_binding目录下:

cmake_minimum_required(VERSION 3.0.0)

set(ThisBinding hello_ext)

find_package(PythonLibs 3.6 REQUIRED)
find_package(Boost COMPONENTS python REQUIRED)

set(CMAKE_SHARED_MODULE_PREFIX "")

add_library(${ThisBinding} MODULE hello_ext.cpp)
target_link_libraries(${ThisBinding} ${Boost_LIBRARIES} ${PYTHON_LIBRARIES})
target_include_directories(${ThisBinding} PRIVATE ${PYTHON_INCLUDE_DIRS})

主目录中的CMakeLists.txt:


cmake_minimum_required(VERSION 3.0.0)

# set the project name
project(longitudinal_control_pid CXX)

# Set some global variables
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED True)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)

enable_testing()
add_subdirectory(googletest)

file(GLOB SOURCES 
    src/*.cpp
)

file(GLOB HEADERS 
    include/*.h
)

add_library(longitudinal_control_pid ${SOURCES})

target_include_directories(longitudinal_control_pid PUBLIC ./)

add_subdirectory(test)
add_subdirectory(py_bindings)

我正在使用Ubuntu 20.04python3。 我想让这个脚本导入构建的共享库并使用绑定

我已经在谷歌上搜索过了,还没有找到适合我的解决方案

有人知道怎么做吗

谢谢


Tags: pytxtproject脚本cmakeaddhellopid