python - Cython:访问 CPython 对象的私有(private) C 成员

标签 python c types cython

http://docs.cython.org/src/userguide/extension_types.html#external-extension-types它解释了如何访问 Python 扩展模块中对象的内部(隐藏或“私有(private)”)C 级成员。

我想从 sqlite3.Connection 对象访问内部成员 db,该对象在文件 的结构 pysqlite_Connection 中定义Python2 源代码的 Modules/_sqlite/connection.h。我这样做:

文件连接.pxd:

cdef extern from "connection.h":
    struct sqlite3Connection:
        sqlite3 *db

    ctypedef class __builtin__.xConnection [object pysqlite_Connection]:
        cdef sqlite3Connection conn

然后像这样使用它:

文件 vtables.pxd:

from connection cimport xConnection

cdef dbname(xConnection c):
    cdef sqlite3 *d
    return sqlite3_db_filename(c.conn.db, "main")

这用 cython 编译,但是当我对结果运行 C 编译器时,我得到:

vtables.c:635:69: error: ‘pysqlite_Connection’ has no member named ‘conn’
   __pyx_t_1 = __Pyx_PyBytes_FromString(sqlite3_db_filename(__pyx_v_c->conn.db, __pyx_k_main)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 6; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
                                                                     ^

生成的 C 代码似乎在访问 pysqlite_Connection 结构而不是包装 xConnection,提示访问成员 conn 当然不在 pysqlite_Connection 中,而是在我的 xConnection Cython 类中。但是在dbname 函数中参数明确定义为xConnection。这似乎是 cython 编译器中的错误。还是我错过了什么?

我尝试按照文档中的方式提供 type 参数,例如:

ctypedef class __builtin__.xConnection [object pysqlite_Connection, type pysqlite_ConnectionType]:
    cdef sqlite3Connection conn

但是 cython 崩溃了。

如果此方法已过时/不再受支持,是否有任何替代方法?

最佳答案

我不认为你已经完成了你认为你已经完成的事情。您尚未创建名为 xConnection 的包装器类。您已向 Cython 保证已经有一个名为 __builtin__.xConnection 的类,并且它是使用 C 结构 pysqlite_Connection 存储的,并且它包含一个 sqlite3Connection 结构,其中包含一个名为 db 的成员。

我想你想告诉 Cython 已经有一个名为 sqlite.Connection 的类,它存储在 C 结构 pysqlite_Connection 中,其中包含一个名为数据库:

cdef extern from "connection.h":
    # I assume you definite this somewhere else
    ctypedef struct sqlite3:
        pass

    ctypedef class sqlite.Connection [object pysqlite_Connection]:
        cdef sqlite3* db

cdef dbname(Connection c):
    return sqlite3_db_filename(c.db, "main")

关于python - Cython:访问 CPython 对象的私有(private) C 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33086984/

相关文章:

arrays - 如何在不知道c中大小的情况下遍历数组

Scala 高级类型语法

c - 如何创建具有未定义类型的独立链接列表标题

Python - 从管道中简单读取行

python - pandas 构建逐行比较矩阵

c++ - 以编程方式释放 libstagrab 中的内存

c - K&R c 编程书籍第二版,练习 3-2,我写的一个微妙错误

MySQL 比较二进制排序规则与二进制字符串

python - 启动应用程序时 Py2App PIL 图像错误

python - SQLite 数据库查询(Python、Bottle)