可以使用pybind11进口模块

发布于 2025-01-27 09:12:45 字数 825 浏览 3 评论 0原文

我正在尝试使用pybind11在C ++中调用Python函数:

#include <pybind11/embed.h>

int main(int argc, char* argv[])
{
    pybind11::scoped_interpreter guard{};
    pybind11::module_ sys = pybind11::module_::import("scripts.hello_world");
    auto func = sys.attr("say_hello");
    func();

    return 0;
}

并且我在Python中有这样的脚本:

def say_hello():
    print("Hello from Python")

但是当我尝试运行Main.cpp时,我会遇到一个错误:

terminate called after throwing an instance of 'pybind11::error_already_set'
  what():  ModuleNotFoundError: No module named 'scripts'

所以,我无法弄清楚为什么Pybind可以' t找到此模块。有人可以帮忙吗?

目录层次结构:

myProject
 ∟.idea
 ∟CMakeLists.txt
 ∟src
   ∟CMakeLists.txt
   ∟main.cpp
   ∟scripts
     ∟__init__.py
     ∟hello_world.py

I'm trying to call a Python function in C++ using pybind11:

#include <pybind11/embed.h>

int main(int argc, char* argv[])
{
    pybind11::scoped_interpreter guard{};
    pybind11::module_ sys = pybind11::module_::import("scripts.hello_world");
    auto func = sys.attr("say_hello");
    func();

    return 0;
}

And I have such script in Python:

def say_hello():
    print("Hello from Python")

But when I am trying to run the main.cpp I get an error:

terminate called after throwing an instance of 'pybind11::error_already_set'
  what():  ModuleNotFoundError: No module named 'scripts'

So, I can't figure out why pybind can't find this module. Can somebody help?

Directories hierarchy:

myProject
 ∟.idea
 ∟CMakeLists.txt
 ∟src
   ∟CMakeLists.txt
   ∟main.cpp
   ∟scripts
     ∟__init__.py
     ∟hello_world.py

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

还不是爱你 2025-02-03 09:12:45

C ++不是Python。您不能只将脚本相对于项目文件夹结构的一个.cpp文件之一,并期望该路径具有任何含义。

一旦整理了程序,您拥有的全部是构建目录中的二进制文件。这取决于您的cmakelists.txt。汇编后,您的项目具有哪些源文件,或者您的项目结构曾经是什么绝对无关。

为了访问文件,您需要提供绝对路径或将脚本文件夹放在程序的工作目录的内部,以防您想使用相对路径。您的工作目录的位置取决于您的启动方式。但是在大多数情况下,它应该只是包含您可执行文件的目录。

C++ isn't Python. You cant just place your scripts relative to one of your .cpp files inside of your project folder structure and expect that path to have any meaning.

Once your program is compiled all you have is a binary in your build directory. Where that is depends on your CMakeLists.txt. What source files your project has or what your project structure used to be is absolutely irrelevant after compilation.

In order to access files you need to either provide the absolute path or place your scripts folder inside of the working directory of your program in case you want to use relative paths. Where your working directory is depends on how your start it. But in most cases it should just be the directory which contains your executable.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文