简体   繁体   English

如何导入我合并到我的 python 模块中的 pybind 模块?

[英]How do I import the pybind module I incorporated into my python module?

I have created a python module that has the following structure (loosely based on this example ):我创建了一个具有以下结构的 python 模块(大致基于此示例):

module_name
├── LICENSE
├── README.md
├── module_name
│   ├── __init__.py
│   └── submodule_name
│       ├── __init__.py
│       └── submodule_name.py
├── setup.py
└── src
    └── sq.cpp

I can run setup.py and install this module without a problem.我可以运行setup.py并毫无问题地安装此模块。 I can also import the pure python modules:我还可以导入纯 python 模块:

import module_name
import module_name.submodule_name

For sq.cpp I have the following in setup.py对于sq.cpp ,我在setup.py中有以下内容

from pybind11 import get_cmake_dir
from pybind11.setup_helpers import Pybind11Extension, build_ext


ext_modules = [
    Pybind11Extension("sq",
    ["src/sq.cpp"],),
]

sq.cpp defines the pybind module as sq.cpp将 pybind 模块定义为

PYBIND11_MODULE(sq, m)
{
    m.doc() = "a function";
    m.def("sq", &sq, "a function");
}

At this point I'm confused about how to load the module in sq.cpp .在这一点上,我对如何在sq.cpp中加载模块感到困惑。 I have tried import sq , import module_name.sq , import sq.sq but all result in a ModuleNotFoundError .我试过import sqimport module_name.sqimport sq.sq ,但都导致ModuleNotFoundError What am I missing?我错过了什么? How am I supposed to import the pybind module?我应该如何导入 pybind 模块? Do I have the structure wrong?我的结构错了吗?

Your build should fail as the names of the module and function are the same.由于模块和函数的名称相同,您的构建应该会失败。 (Look at sq.cpp ) When you define a module with PYBIND11_MODULE(sq, m) , the sq becomes a local variable and &sq will reffer to another object, but not to the sq function. (查看sq.cpp )当您使用PYBIND11_MODULE(sq, m)定义模块时, sq成为局部变量, &sq将引用另一个对象,而不是sq函数。 So you can rename the name of the function to keep the module name as sq .因此,您可以重命名函数的名称以保持模块名称为sq

#include <pybind11/pybind11.h>

void _sq() {}

PYBIND11_MODULE(sq, m) {

    m.doc() = "a function";
    m.def("sq", &_sq, "a function");
}

Compare the following setup.py with yours将以下setup.py与您的进行比较

import sys

from pybind11 import get_cmake_dir
from pybind11.setup_helpers import Pybind11Extension, build_ext
from setuptools import setup

__version__ = "0.0.1"

ext_modules = [
    Pybind11Extension("sq",
                      ["src/sq.cpp"],
                      define_macros=[('VERSION_INFO', __version__)],
                      ),
]

setup(
    name="sq",
    version=__version__,
    ext_modules=ext_modules,
    cmdclass={"build_ext": build_ext},
    zip_safe=False,
    python_requires=">=3.6",
)

Install the module安装模块

Redirect to the parent directory of the sq module directory and execute the following command.重定向到sq模块目录的父目录,执行如下命令。

python3 -m pip install ./sq

Import the module导入模块

import sq

sq.sq()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM