标签: python-c-api

Python C API:打开PyObject类型

我有一些代码可以将Python与C++接口,但是每次看到它我都认为必须有更好的方法.在C++方面,有一个'variant'类型可以处理固定范围的基本类型 - int,real,string,variant变量等.我有一些代码使用Python API从等效的Python类型转换.它看起来像这样:

variant makeVariant(PyObject* value)
{  
  if (PyString_Check(value)) {
    return PyString_AsString(value);
  }
  else if (value == Py_None) {
    return variant();
  }
  else if (PyBool_Check(value)) {
    return value == Py_True;
  }
  else if (PyInt_Check(value)) {
    return PyInt_AsLong(value);
  }
  else if (PyFloat_Check(value)) {
    return PyFloat_AsDouble(value);
  }
  // ... etc
Run Code Online (Sandbox Code Playgroud)

问题是链式if-else ifs.它似乎是在调用switch语句,或者由类型标识符键入的创建函数的表或映射.换句话说,我希望能够写出如下内容:

  return createFunMap[typeID(value)](value);
Run Code Online (Sandbox Code Playgroud)

基于API文档的略读,直接获取'typeID'的最佳方法并不明显.我知道我可以这样做:

  PyTypeObject* type = value->ob_type;
Run Code Online (Sandbox Code Playgroud)

这显然让我快速了解类型信息,但是使用它与我感兴趣的有限类型集相关的最简洁方法是什么?

c python python-c-api python-c-extension

7
推荐指数
1
解决办法
4577
查看次数

我怎样才能从Python C代码断言?

我正在用C编写一个Python类,我想在我的调试代码中加入断言.assert.h很适合我.这只会被放入调试编译中,因此不会出现影响Python代码*用户的断言失败的可能性.

我试图划分我的'库'代码(它应该与链接到Python的代码分开),所以我可以从其他C代码中使用它.因此,我的Python方法是我的纯C代码的薄包装.

所以我不能在我的'库'代码中执行此操作:

if (black == white)
{
    PyErr_SetString(PyExc_RuntimeError, "Remap failed");
}
Run Code Online (Sandbox Code Playgroud)

因为这会用Python污染我的纯C代码.它也比简单的更丑陋

assert(black != white);
Run Code Online (Sandbox Code Playgroud)

我相信Distutils编译器总是设置NDEBUG,这意味着我assert.h甚至不能在调试版本中使用.

Mac OS和Linux.

救命!

*我听过一个论点反对在Python中调用C代码断言.

c python distutils python-c-api python-c-extension

7
推荐指数
1
解决办法
1221
查看次数

全局解释器锁定和访问数据(例如,对于NumPy阵列)

我正在为Python编写一个C扩展,它应该在对数据进行操作时释放全局解释器锁.我认为我已经很好地理解了GIL的机制,但仍然存在一个问题:当线程不拥有GIL时,我可以访问Python对象中的数据吗?例如,我想从C函数中的(大)NumPy数组中读取数据,而我仍然希望允许其他线程在其他CPU内核上执行其他操作.C函数应该

  • 发布GIL Py_BEGIN_ALLOW_THREADS
  • 无需使用Python函数即可读取和处理数据
  • 甚至将数据写入先前构造的NumPy数组
  • 重新获取GIL Py_END_ALLOW_THREADS

这样安全吗?当然,其他线程不应该改变C函数使用的变量.但也许有一个隐藏的错误来源:Python解释器可以移动一个对象,例如.通过某种垃圾收集,而C函数在一个单独的线程中工作?

为了用最小的例子说明问题,请考虑下面的(最小但完整的)代码.用它编译它(在Linux上)

gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -fPIC -I/usr/lib/pymodules/python2.7/numpy/core/include -I/usr/include/python2.7 -c gilexample.c -o gilexample.o
gcc -pthread -shared gilexample.o -o gilexample.so
Run Code Online (Sandbox Code Playgroud)

用Python测试它

import gilexample
gilexample.sum([1,2,3])
Run Code Online (Sandbox Code Playgroud)

是之间的代码Py_BEGIN_ALLOW_THREADS和Py_END_ALLOW_THREADS安全吗?它访问Python对象的内容,我不想在内存中复制(可能很大)数组.

#include <Python.h>
#include <numpy/arrayobject.h>

// The relevant function
static PyObject * sum(PyObject * const self, PyObject * const args) {
  PyObject * X;
  PyArg_ParseTuple(args, "O", &X);
  PyObject const * const X_double = PyArray_FROM_OTF(X, NPY_DOUBLE, NPY_ALIGNED);
  npy_intp const size = PyArray_SIZE(X_double);
  double * const …
Run Code Online (Sandbox Code Playgroud)

python numpy python-c-api

7
推荐指数
2
解决办法
2248
查看次数

通过C-API访问Numpy Recarray

如果我们有一个Numpy重新组合: x = np.array([(1.,2.)], dtype=np.dtype([('a','<f8'),('b','<f8')]))
我们可以在Python中访问它的字段:
x['a']或者x['b']
如果这个数组被传递给C程序,PyArrayObject我们如何访问它的字段?
我意识到我们可以通过C获取dtype:PyArray_Descr *dtype = PyArray_DTYPE(arr)
PyObject *fields = dtype->fields但是如何使用它来访问数据x['a']?

python numpy python-c-api recarray

7
推荐指数
1
解决办法
645
查看次数

c ++中的嵌入式python代码 - 导入python库时出错

我试图使用嵌入在C++程序中的Python 3.5解释器从C++接收图像,并将其用作我训练的张量流模型的输入.首先,我将我的图像转换为numpy数组,然后将其发送到python.这是我的简化代码,工作正常(从这里采用的代码):

Python代码:

def multiply_fun(M):
    V = M*2
    print(V)
Run Code Online (Sandbox Code Playgroud)

调用上述函数的我的C++代码:

#include <Python.h>
#include <abstract.h>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <ndarrayobject.h>
#include <vector>


int main()
{
    Py_InitializeEx(1);

    PyObject* sysPath = PySys_GetObject((char*)"path");
    PyObject* curDir = PyUnicode_FromString(".");
    PyList_Append(sysPath, curDir);
    Py_DECREF(curDir);

    PyObject* python_code = PyImport_ImportModule("python_code");
    PyObject* multiply_fun = PyObject_GetAttrString(python_code, "multiply_fun");
    Py_XDECREF(python_code);

    import_array1(-1);
    npy_intp dim[] = { 5, 5 };
    std::vector<double> buffer(5*5, 1);

    PyObject* array_2d = PyArray_SimpleNewFromData(2, dim, NPY_DOUBLE, &buffer[0]);
    PyObject* return_value1 = PyObject_CallFunction(multiply_fun, "O", array_2d);

    Py_XDECREF(return_value1);
    Py_XDECREF(array_2d);
    Py_XDECREF(multiply_fun);

    Py_Finalize();
    return 0;
} 
Run Code Online (Sandbox Code Playgroud)

但是,当我想使用大多数python库时,我收到一个错误.例如,对于这个python代码: …

c++ python python-embedding python-c-api

7
推荐指数
1
解决办法
1397
查看次数

使用具有cppyy的Eigen库

我已经成功地使用cppyy为我正在研究的C++项目进行自动python绑定.我最近加入了Eigen库,但是我很难和cppyy一起使用它.有没有人有这方面的经验,或者知道我应该怎么做?

我有回购的以下结构(仅显示相关部分):

.
??? CMakeLists.txt
??? build
??? external
   ?? eigen
??? include
   ?? all .hpp files
??? src
   ?? all .cpp files
??? python
   ?? qmc.py
Run Code Online (Sandbox Code Playgroud)

这里external/eigen是Eigen GitHub回购的副本.该qmc.py文件是cppyy魔法发生的地方,它看起来像这样(在尝试添加Eigen之前,这个工作正常)

import cppyy
import tempfile
import os
import glob

try:
    current_dir = os.path.dirname(__file__)
except NameError:
    current_dir = os.getcwd()
source_dir = os.path.dirname(current_dir)
install_dir = os.path.join(source_dir, 'build')
include_dir = os.path.join(source_dir, 'include')
eigen_dir = os.path.join(source_dir, 'external', 'eigen')
print(current_dir, source_dir, include_dir, install_dir)

def cmake_run(build_type='Release', c_compiler='gcc', cxx_compiler='g++'): …
Run Code Online (Sandbox Code Playgroud)

c++ python python-c-api eigen

7
推荐指数
1
解决办法
392
查看次数

具有 Python C 扩展的类(而不是方法)的完整且最小的示例?

在任何地方,我都可以轻松找到有关使用Python C 扩展编写方法并在 Python 中使用它的示例。就像这个:Python 3 扩展示例

$ python3
>>> import hello
>>> hello.hello_world()
Hello, world!
>>> hello.hello('world')
Hello, world!
Run Code Online (Sandbox Code Playgroud)

如何编写一个 hello word 全功能 Python 类(而不仅仅是一个模块方法)?

我认为这How towrapp a C++ object using pure Python Extension API (python3)? 问题有一个例子,但它似乎并不小,因为他在上面使用(或包装?)C++ 类。

例如:

$ python3
>>> import hello
>>> hello.hello_world()
Hello, world!
>>> hello.hello('world')
Hello, world!
Run Code Online (Sandbox Code Playgroud)

这个带有 C 扩展的 Python 类示例的等价物是什么?

我会这样使用它:

from .mycextensionsmodule import ClassName

classname = ClassName("Hello")
classname.talk( 'world!' )
# prints "Hello world!"
Run Code Online (Sandbox Code Playgroud)

我的目标是编写一个完全用 C 编写的类以提高性能(我的项目中的所有其他类都将使用 Python,除了这个)。我并不是在寻找使用 …

python cpython class python-c-api python-3.x

7
推荐指数
1
解决办法
2639
查看次数

C 扩展 - 如何将 printf 重定向到 python 记录器?

我有一个简单的 C 扩展(参见下面的示例),有时使用 printf 函数进行打印。我正在寻找一种方法来包装对 C 扩展中的函数的调用,以便所有这些 printfs 将被重定向到我的 python 记录器。

你好ç:

#include <Python.h>

static PyObject* hello(PyObject* self)
{
   printf("example print from a C code\n");
   return Py_BuildValue("");
}

static char helloworld_docs[] =
   "helloworld(): Any message you want to put here!!\n";

static PyMethodDef helloworld_funcs[] = {
   {"hello", (PyCFunction)hello,
   METH_NOARGS, helloworld_docs},
   {NULL}
};

static struct PyModuleDef cModPyDem =
{
    PyModuleDef_HEAD_INIT,
    "helloworld",
    "Extension module example!",
    -1,
    helloworld_funcs
};

PyMODINIT_FUNC PyInit_helloworld(void)
{
    return PyModule_Create(&cModPyDem);
};
Run Code Online (Sandbox Code Playgroud)

设置.py:

from distutils.core import setup, Extension
setup(name = 'helloworld', …
Run Code Online (Sandbox Code Playgroud)

logging stdout python-c-api python-3.x python-logging

7
推荐指数
1
解决办法
2601
查看次数

您可以在 C 扩展中安全地更改 Python 对象的类型吗?

问题

\n

假设我使用 C 扩展 API 实现了两种 Python 类型,并且这些类型是相同的(相同的数据布局/C struct),除了它们的名称和一些方法之外。假设所有方法都遵循数据布局,您可以在 C 函数中安全地将对象的类型从其中一种类型更改为另一种类型吗?

\n

值得注意的是,从 Python 3.9 开始,似乎有一个 function Py_SET_TYPE,但文档并不清楚是否/何时可以安全地执行此操作。我有兴趣了解如何安全地使用此函数以及在 3.9 版本之前是否可以安全地更改类型。

\n

动机

\n

我正在编写一个 Python C 扩展来实现持久哈希数组映射 Trie (PHAMT);如果它有用,源代码在这里(截至撰写本文时,它位于此提交)。我想添加的一个功能是能够从 PHAMT 创建瞬态哈希数组映射 Trie (THAMT)。THAMT 可以及时从 PHAMT 中产生O(1),并且可以有效地就地突变。重要的是,THAMT 与 PHAMT\xe2\x80\x94 具有完全相同的底层C 数据结构。PHAMT和 THAMT 之间的唯一真正区别是它们的 Python 类型封装的一些方法。这种通用结构允许人们在完成一组编辑后非常有效地将 THAMT 转换回 PHAMT。(当对 PHAMT 执行大量更新时,此模式通常会减少内存分配的数量)。

\n

实现从 THAMT 到 PHAMT 的转换的一种非常方便的方法是简单地将 THAMT 对象的类型指针从 THAMT 类型更改为 PHAMT 类型。我相信我可以编写安全地导航此更改的代码,但我可以想象这样做可能会破坏 Python 垃圾收集器。

\n

(需要明确的是:动机只是问题如何产生的背景。我不是在寻求实现动机中描述的结构的帮助, …

python types cpython python-c-api python-3.x

7
推荐指数
1
解决办法
306
查看次数

没有 GIL 的 Python 中的隔离子解释器

有PEP-554和PEP-684。两者都旨在支持线程级别的多个解释器。

有谁知道这些 PEP 是否至少在 Python 的实验版本或预发布版本(如 3.11)中实现?

我发现 Python 3.10(甚至可能是 3.9)在实验版本中具有这些功能。如果您通过配置以下标志来构建 CPython:

./configure --with-experimental-isolated-subinterpreters

或者在编译所有文件时在编译命令中添加define .c:

#define EXPERIMENTAL_ISOLATED_SUBINTERPRETERS 1

我在一个著名的项目中发布了启用此功能的请求,请参阅此处的问题。

启用此功能后,我想我将能够在多个线程(而不是进程)内创建单独的解释器,这意味着我不再需要多重处理。

更重要的是,根据此功能描述,当使用多个解释器时,不需要有单个 GIL,单独线程中的每个解释器都有自己的 GIL。这意味着即使解释器是在线程内创建的,仍然会使用所有 CPU 核心,就像multiprocessing. 当前的 Python 遭受 GIL 的困扰只是因为它强制只使用单个 CPU 核心,因此multiprocessing人们使用所有 CPU 核心来克服这个问题。

在描述这些功能时,据说作者必须手动修改 1500 个静态和全局变量,将它们全部移动到线程状态结构内的每线程本地表中。

想必所有这些新功能现在只能通过Python C API来使用。

如果这里有人知道如何使用这些独立的子解释器功能,您能否提供一些 Python 代码或 C API 代码以及如何使用它们的详细示例?

具体来说,我感兴趣的是如何以使用所有CPU核心的方式使用解释器,即我想知道如何避免单个GIL,而是使用多个GIL(实际上是本地锁,LIL)。当然,我想要内部线程,而不使用multiprocessing.

python multithreading interpreter python-c-api gil

7
推荐指数
0
解决办法
474
查看次数