最简单的例子:
Object.hCythonMinimal.pyxsetup.py
Object.h的内容:
class Object {public: Object clone() { Object o; return o; }};
CythonMinimal.pyx的内容:
cdef extern from "Object.h": cdef cppclass _Object "Object": _Object() except + _Object clone()cdef class Object: cdef _Object *thisptr def __cinit__(self): self.thisptr = new _Object() def __dealloc__(self): del self.thisptr def clone(self): return self.thisptr.clone()
setup.py的内容
from distutils.core import setupfrom distutils.extension import Extensionfrom Cython.Build import cythonizefrom Cython.distutils import build_extimport osos.environ["CC"] = "g++-4.7"os.environ["CXX"] = "g++-4.7"modules = [Extension("CythonMinimal",["CythonMinimal.pyx"],language = "c++",extra_compile_args=["-std=c++11"],extra_link_args=["-std=c++11"])]for e in modules: e.cython_directives = {"embedsignature" : True}setup(name="CythonMinimal",cmdclass={"build_ext": build_ext},ext_modules=modules)
这是我在编译时得到的错误:
cls ~/workspace/CythonMinimal $python3 setup.py buildrunning buildrunning build_extcythoning CythonMinimal.pyx to CythonMinimal.cppError compiling Cython file:------------------------------------------------------------... def __dealloc__(self): del self.thisptr def clone(self): return self.thisptr.clone() ^------------------------------------------------------------ CythonMinimal.pyx:18:27: Cannot convert '_Object' to Python object building 'CythonMinimal' extension creating build creating build/temp.macosx-10.8-x86_64-3.3 g++-4.7 -Wno-unused-result -fno-common -dynamic -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I/usr/local/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/include/python3.3m -c CythonMinimal.cpp -o build/temp.macosx-10.8-x86_64-3.3/CythonMinimal.o -std=c++11 cc1plus: warning: command line option '-Wstrict-prototypes' is valID for C/ObjC but not for C++ [enabled by default] CythonMinimal.cpp:1:2: error: #error Do not use this file,it is the result of a Failed Cython compilation. error: command 'g++-4.7' Failed with exit status 1
我假设_Object.clone需要返回一个_Object(cppclass类型),但是Objet.clone应该返回一个Object(Python类型).但是怎么样?
解决方法 您正在python函数中返回一个C对象,该对象只允许返回python对象:def clone(self): return self.thisptr.clone()
这样做:
cdef _Object clone(self) except *: return self.thisptr.clone()
但这取决于你想要做什么,你可能想要返回Object而不是_Object,所以我会这样修改它:
cdef class Object: cdef _Object thisobj cdef _Object *thisptr def __cinit__(self,Object obj=None): if obj: self.thisobj = obj.thisobj.clone() self.thisptr = &self.thisobj def __dealloc__(self): pass def clone(self): return Object(self)总结
以上是内存溢出为你收集整理的如何在Cython中返回新的C对象?全部内容,希望文章能够帮你解决如何在Cython中返回新的C对象?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)