【问题标题】:undefined symbol: _PyThreadState_Current when using pybind wrapped C++ code未定义符号:使用 pybind 包装的 C++ 代码时的 _PyThreadState_Current
【发布时间】:2022-01-26 00:56:59
【问题描述】:

当我运行bazel test ... 时,cpp 代码将编译,但 Python 卡住了。 我在写这个问题之前阅读了这些,但我找不到任何解决方案:

https://github.com/pybind/pybind11/issues/314

undefined symbol: _PyThreadState_Current when importing tensorflow

https://github.com/carla-simulator/ros-bridge/issues/368

https://python-forum.io/thread-32297.html

操作系统: Linux 5.11.0-43-generic #47~20.04.2-Ubuntu SMP Mon Dec 13 11:06:56 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux

Python:Python 3.8.10

g++:g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0

pybind11:v2.8.1

C++ 代码:

//math.cc
#include <pybind11/pybind11.h>

int add(int i, int j) {
  return i + j;
}

int subtract(int i, int j) {
  return i - j;
}

namespace py = pybind11;

PYBIND11_MODULE(math, m) {
  m.def("add", &add);

  m.def("subtract", &subtract);
}

Python 代码:

#math_test.py
from module import t_math

assert t_math.add(1, 1) == 2
assert t_math.subtract(1, 1) == 0

构建:

load("@pybind11_bazel//:build_defs.bzl", "pybind_extension")

pybind_extension(
  name = "t_math",
  srcs = ["math.cc"],
)
    
py_test(
  python_version = "PY3",
  name = "math_test",
  size = "small",
  srcs = ["math_test.py"],
  data = [":t_math.so"],
)

错误:

Traceback(最近一次调用最后一次):文件 "/home/user/.cache/bazel/_bazel_user/a768e2cde210bf677ee66cfded678e04/sandbox/linux-sandbox/52/execroot/ma​​in/bazel-out/k8-fastbuild/bin/module/math_test.runfiles/ /module/math_test.py", 第 7 行,在 从模块导入 t_math ImportError: /home/user/.cache/bazel/_bazel_user/a768e2cde210bf677ee66cfded678e04/sandbox/linux-sandbox/52/execroot/ma​​in/bazel-out/k8-fastbuild/bin/module /math_test.runfiles/ma​​in/module/t_math.so: 未定义符号:_PyThreadState_Current

【问题讨论】:

    标签: python c++ bazel pybind11


    【解决方案1】:

    有两个问题:

    1. PYBIND11_MODULE宏的第一个参数必须和pybind_extension中的一样
    2. 此环境变量必须设置为:PYTHON_BIN_PATH=$(which python3)

    固定示例

    # BUILD
    load("@pybind11_bazel//:build_defs.bzl", "pybind_extension")
    
    pybind_extension(
      name = "new_math",
      srcs = ["ex.cpp"],
    )
        
    py_test(
      python_version = "PY3",
      name = "math_test",
      size = "small",
      srcs = ["math_test.py"],
      data = ["new_math.so"],
    )
    
    // ex.cpp
    #include <pybind11/pybind11.h>
    
    int add(int i, int j) {
      return i + j;
    }
    
    int subtract(int i, int j) {
      return i - j;
    }
    
    namespace py = pybind11;
    
    PYBIND11_MODULE(new_math, m) {
      m.def("add", &add);
    
      m.def("subtract", &subtract);
    }
    
    # math_test.py
    from module import new_math
    
    assert new_math.add(1, 1) == 2
    assert new_math.subtract(1, 1) == 0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多