【问题标题】:Cython: How to export C++ class to .hpp header instead of C .h headerCython:如何将 C++ 类导出到 .hpp 标头而不是 C .h 标头
【发布时间】:2021-12-20 10:17:36
【问题描述】:

这在 .pxd 文件中可以正常工作:

cdef public:
    struct foo:
        float bar

但这不起作用:

cdef public:
    class foo:
        float bar # Syntax error in simple statement list

这可行,但 Cython 仍在制作 struct 而不是 class 并且生成的文件是 .h 文件而不是 .hpp(或 .hh)文件:

cdef public:
    cppclass foo:
        float bar

我的文件名为 mod.pyx,Cython 将上面的 cppclass 转换为:

#ifndef __PYX_HAVE__mod
#define __PYX_HAVE__mod

#include "Python.h"
struct foo;
struct foo {

  /* "mod.pyx":21
 *
 * cdef public:
 *     cppclass foo:             # <<<<<<<<<<<<<<
 *         float bar
 *
 */
  float bar;
};

如何从 Cython 转译中生成真正的 C++ 输出?我的意思是 .hpp 或 .hh 文件,里面有 class 关键字。可以改用单独的 C++ 头文件,但我想让源代码完全使用 Cython。

转译命令为:
cython3 -3 --cplus --fast-fail mod.pyx

【问题讨论】:

    标签: python c++ header cython transpiler


    【解决方案1】:

    我已经弄清楚如何仅在 Cython 中定义 C++ 类(不是 Python 扩展类型“类”);它仍然被转换为.h 文件作为struct 里面有方法

    # Declaration
    cdef public:
        cppclass foo:
            float bar
            foo() # Constructor
            method() # Sample method
    
    # Implementation
    cdef cppclass foo:
        method():
            cdef foo* p = this # 'this' can be used
            print(p.bar+1) # Test
    

    有一些注意事项:

    • nullary 构造函数是必须的,Cython 这么说
      • 这不需要构造函数:cdef foo* f = new foo()
      • 这需要一个构造函数:cdef foo f = foo()
        • 或错误:no constructor found for C++ type 'foo'
    • Python 中没有重载,这适用于 Cython,因此没有构造函数重载 (?);属性改为由方法设置

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-06
      • 2021-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多