【问题标题】:Pybind11 and global C variablesPybind11 和全局 C 变量
【发布时间】:2018-07-20 09:27:45
【问题描述】:

我无法使用 pybind11 将全局变量从 C 导出到 Python。这个问题可以从一个简单的例子中重现。假设我们有一个像这样的头文件(global.h):

#ifndef GLOBAL_H
#define GLOBAL_H

extern int array[];

#endif 

数组在 C 文件 (global.c) 中定义如下:

#include "global.h"

int array[] = {1, 2, 3, 4};

我想使用 pybind11 和以下 C++ 文件 (pyglobal.cpp) 将这个数组导出到 Python 模块中:

#include <pybind11/pybind11.h>

extern "C"
{
  #include "global.h"
}

PYBIND11_MODULE(pyglobal, m)
{
  m.attr("array") = array;
}

当我使用 CMake (CMakeLists.txt) 生成库时,一切正常:

cmake_minimum_required(VERSION 2.8.12)
project(pyglobal)

find_package(pybind11 PATHS ${PYBIND11_DIR} REQUIRED)

pybind11_add_module(pyglobal pyglobal.cpp global.c)

但是当我启动一个 python3 shell 并输入

import pyglobal

我收到以下错误消息:

> Python 3.5.2 (default, Nov 23 2017, 16:37:01) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pyglobal
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: AttributeError: array

我在这里做错了什么?

【问题讨论】:

  • 我不知道 pybind11 是否可以/不能这样做。但是为什么你需要一个全局变量呢?如果你真的需要它,你可以在库的 python 部分定义它。如果全局变量包含您在使用 C++ 宏进行编译期间获得的数字,则可以创建一个 C++ 函数以将其返回一次。然后在 python 端,创建一个全局变量来保存该值。
  • 我不同意您的评论,但我的问题涉及 pybind11 和全局静态数组:我想知道是否可以使用此库导出这样的数组。我正在比较不同的解决方案(ctypes、cython、swig、boost.python、pybind11、swig),这就是我提出问题的原因。

标签: pybind11


【解决方案1】:

这个赋值是一个相当不幸的隐式转换,因此不会做你认为它做的事情。以下是公开该数组的一种方法,假设您安装了 numpy:

#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>

extern "C"
{
  #include "global.h"
}

PYBIND11_MODULE(pyglobal, m)
{
  auto dtype = pybind11::dtype(pybind11::format_descriptor<int>::format());
  m.attr("array") = pybind11::array(dtype, {3}, {sizeof(int)}, array, nullptr);
}

如果你不知道大小,你可以使用一个空的基本数组和一个大的(假的)大小。请确保不要以范围限制方式以外的任何方式迭代数组。示例:

#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>

extern "C"
{
  #include "global.h"
}

PYBIND11_MODULE(pyglobal, m)
{
  auto dtype = pybind11::dtype(pybind11::format_descriptor<int>::format());
  auto base = pybind11::array(dtype, {(unsigned)-1}, {sizeof(uintptr_t)});
  m.attr("array") = pybind11::array(dtype, {(unsigned)-1}, {sizeof(int)}, array, base);
}

可以这样使用:

>>> import pyglobal
>>> for i in range(3):
...     print(pyglobal.array[i])
... 
1
3
0
>>>

但是例如不能打印,因为它会遍历整个(unsigned)-1 大小。

【讨论】:

    猜你喜欢
    • 2012-01-07
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    • 2015-10-04
    • 2014-11-19
    • 2010-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多