我试图让cython将Python类存储为C ++类,以便以后通过C ++代码进行操作,并且能够将C ++类作为Python类获取,以便以后通过Python代码进行操作。
我一直在“无法将Class1转换为Python对象”。
我做错了什么?
以下是所有代码:
class1.h
#ifndef CLASS1 // header guards
#define CLASS1
using namespace std;
namespace cls {
class Class1 {
public:
Class1();
~Class1();
};
}
#endif
class1.cpp
#include "class1.h"
using namespace cls;
Class1::Class1()
{
}
Class1::~Class1()
{
}
class2.h
#ifndef CLASS2 // header guards
#define CLASS2
using namespace std;
#include "class1.h"
namespace cls {
class Class2 {
private:
Class1 cpp_class;
public:
Class2();
~Class2();
Class1& get_class();
void set_class(const Class1 &c);
};
}
#endif
class2.cpp
#include "class2.h"
#include "class1.h"
using namespace cls;
Class2::Class2()
{
cpp_class = new Class1();
}
Class2::~Class2()
{
delete cpp_class;
}
const Class1& Class2::get_class()
{
return cpp_class;
}
void Class2::set_class(const Class1 &c)
{
cpp_class = c;
}
pyclasses.pxd
import cython
cdef extern from "class1.h" namespace "cls":
cpdef cppclass Class1:
Class1()
cdef extern from "class2.h" namespace "cls":
cpdef cppclass Class2:
Class2()
Class1 get_class()
void set_class(Class1)
pyclasses.pyx
cimport pyclasses
from pyclasses cimport Class1, Class2
cdef class PyClass1:
cdef Class1 *thisptr
def __init__(self):
self.thisptr = new Class1()
def __dealloc__(self):
del self.thisptr
cdef class PyClass2:
cdef Class2 *thisptr
def __init__(self):
self.thisptr = new Class2()
def __dealloc__(self):
del self.thisptr
def getClass(self):
return self.thisptr.get_class()
def setClass(self, Class1 c):
self.thisptr.set_class(c)
setup.py
from distutils.core import setup
from Cython.Build import cythonize
from distutils.extension import Extension
sourcefiles = ['class1.cpp', 'class2.cpp', 'pyclasses.pyx']
compile_opts = ['-std=c++11', '-I../include']
ext=[Extension('pyclass',
sourcefiles,
extra_compile_args=compile_opts,
language='c++')
]
setup(
ext_modules=cythonize(ext)
)
编译命令
python setup.py build_ext --inplace