如何在Cython构建一个iostream对象(例如Cout)并将其传递到C 函数
How to build in Cython an iostream object (e. g. cout) and pass it to a c++ function?
我正在尝试包装以下C 类:
print.h
#include <string>
using namespace std;
class ControlParameters
{
public:
ControlParameters();
~ControlParameters();
void Initialize(string input, ostream& log);
};
print.cpp
#include "print.h"
#include <iostream>
ControlParameters::ControlParameters()
{
}
ControlParameters::~ControlParameters()
{
}
void ControlParameters::Initialize(string input, ostream& log)
{
log<<"Output = "<< input <<endl;
}
我的string.pyx看起来如下:
from libcpp.string cimport string
cdef extern from "<iostream>" namespace "std":
cdef cppclass ostream:
┆ ostream& write(const char*, int) except +
cdef extern from "print.h":
cdef cppclass ControlParameters:
┆ ControlParameters() except +
┆ void Initialize(string, ostream&)
cdef class PyControlParameters:
cdef ControlParameters *thisptr
def __cinit__(self):
┆ self.thisptr = new ControlParameters()
def __dealloc__(self):
┆ del self.thisptr
def PyInitialize(self, a,b):
self.thisptr.Initialize(a, b)
编译string.pyx后,我会收到以下错误:
Compiling String.pyx because it changed.
[1/1] Cythonizing String.pyx
Error compiling Cython file:
------------------------------------------------------------
...
def __cinit__(self):
self.thisptr = new ControlParameters()
def __dealloc__(self):
del self.thisptr
def PyInitialize(self, a,b):
self.thisptr.Initialize(a, b)
^
------------------------------------------------------------
String.pyx:18:39: Cannot convert Python object to 'ostream'
Traceback (most recent call last):
File "setup.py", line 7, in <module>
language="c++"
File "/usr/local/lib/python2.7/dist-packages/Cython/Build/Dependencies.py", line 1039, in cythonize
cythonize_one(*args)
File "/usr/local/lib/python2.7/dist-packages/Cython/Build/Dependencies.py", line 1161, in cythonize_one
raise CompileError(None, pyx_file)
Cython.Compiler.Errors.CompileError: String.pyx
我在这里读到,我必须构建自己的Ostream类才能获取一个Ostream对象。但是如何定义这个对象?我认为我需要一个将我的Python对象转换为Ostream对象的函数。我如何实现此类函数?
如果您始终想将其发送到COUT,那么最简单的方法是在Cython中进行此操作,而不是处理Python中的第二个参数。将COUT添加到您的cdef extern
:
cdef extern from "<iostream>" namespace "std":
# define ostream as before
ostream cout
然后在do pyinitialize中为:
def PyInitialize (self, a):
self.thisptr.Initialize(a,cout)
节省了为Cython编写完整的Ostream包装班的努力。
相关文章:
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 在 COUT 语句中使用 COUT 调用函数
- 在这种情况下显式调用时,std::cout 如何更改析构函数的行为?
- C++代码停止工作错误使用cout内部函数
- 指针变量在 cout 函数中不起作用
- 如果我想使用 cout 为我的函数提供任何输入......我该如何给出
- 使用<<自有函数的运算符来"override" cout
- std::cout 在打印变量与函数表达式时的行为不同
- 是否可以在每次使用std::cout时执行一个函数
- 不能 std::cout 一个max_element函数
- 打印一个带有静态 int 的函数,有一个 std::cout 和多个 std::cout 有什么区别?
- cout 一个类的函数
- 为什么 cout 语句在传递指向函数的指针时没有执行?
- 将参数传递给成员函数,就像使用 std::cout 一样
- 函数不返回值,但 cout 显示它
- 如何使用 std::cout 或 std::ofstream 作为单个函数的输入?
- COUT 内部函数调用的顺序
- 为什么调用 cout.operator<<(const char*) 打印地址而不是字符串? 如何创建一个函数本地静态"HashSet<char>"并初始化它一次?
- Cin和Cout在构造函数中
- 是否可以在C++中的文件中显示void函数cout输出