refactor(build): restructure package layout and fix CMake build directory restoration

- Update pybind_src to point to project root instead of dm_imu subdirectory
- Change CMakeExtension module from "imu_py" to "dm_imu.imu_py"
- Switch to find_packages() with package_dir for automatic package discovery
- Add saving/restoring of CWD in CMake build to prevent directory side effects
This commit is contained in:
2025-12-10 21:11:21 +08:00
parent ced3669fac
commit 35efbfc91a
7 changed files with 28 additions and 4 deletions

21
CMakeLists.txt Normal file
View File

@@ -0,0 +1,21 @@
cmake_minimum_required(VERSION 3.14)
project(imu_py LANGUAGES CXX)
# 使用 C++17
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# 查找 pybind11已通过 pip 安装)
execute_process(COMMAND ${PYTHON_EXECUTABLE} -c "import pybind11; print(pybind11.get_cmake_dir())" OUTPUT_VARIABLE PYBIND11_CMAKE_DIR OUTPUT_STRIP_TRAILING_WHITESPACE)
set(CMAKE_PREFIX_PATH "${PYBIND11_CMAKE_DIR}" ${CMAKE_PREFIX_PATH})
include_directories(
${CMAKE_CURRENT_SOURCE_DIR}/dm_imu/src
)
find_package(pybind11 REQUIRED)
pybind11_add_module(imu_py
dm_imu/pybind_imu.cpp
dm_imu/src/imu_driver.cpp
dm_imu/src/bsp_crc.cpp)

View File

@@ -2,6 +2,7 @@ LICENSE
README.md
pyproject.toml
setup.py
./dm_imu/__init__.py
dm_imu/__init__.py
dm_imu.egg-info/PKG-INFO
dm_imu.egg-info/SOURCES.txt

View File

@@ -1,2 +1 @@
dm_imu
imu_py

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -41,15 +41,17 @@ class CMakeBuild(build_ext):
]
# 1) configure
old_cwd = os.getcwd()
os.chdir(str(build_temp))
self.spawn(["cmake", str(ext.sourcedir)] + cmake_args)
# 2) build
self.spawn(
["cmake", "--build", ".", "--config", cfg, "--", f"-j{os.cpu_count() or 1}"],
)
os.chdir(old_cwd)
# Path to the pybind11 C++ source directory.
pybind_src = pathlib.Path(__file__).parent / "dm_imu"
pybind_src = pathlib.Path(__file__).parent
setup(
name="dm_imu",
@@ -58,8 +60,9 @@ setup(
description="DM IMU driver with pybind11",
long_description=open("README.md", encoding="utf-8").read(),
long_description_content_type="text/markdown",
packages=["dm_imu"],
ext_modules=[CMakeExtension("imu_py", sourcedir=str(pybind_src))],
packages=find_packages(where="."),
package_dir={"": "."},
ext_modules=[CMakeExtension("dm_imu.imu_py", sourcedir=str(pybind_src))],
cmdclass={"build_ext": CMakeBuild},
zip_safe=False,
python_requires=">=3.8",