Skip to content

Instantly share code, notes, and snippets.

@bjodah
Created August 31, 2015 12:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjodah/70f330a4bc361b1a4b8e to your computer and use it in GitHub Desktop.
Save bjodah/70f330a4bc361b1a4b8e to your computer and use it in GitHub Desktop.
deferred_declaration_cython
# -*- coding: utf-8 -*-
# distutils: language = c++
from libcpp cimport bool
cdef extern from "myheader.hpp":
cdef cppclass MyInt:
void add_two()
bool is_poitive()
cdef cppclass MyFloat:
void add_two()
bool is_poitive()
cdef class PyBase:
cdef void * thisptr;
def add_two(self):
self.thisptr.add_two()
def is_poitive(self):
return self.thisptr.is_poitive()
# Is it possible to define "add_two" and "is_positive" only in PyBase?
# or do I need to have copies of these methods in each cdef class below?
cdef class PyMyInt(PyBase):
def __cinit__(self, int val):
self.thisptr = <void *>(new MyInt(val))
def __dealloc__(self):
del self.thisptr
cdef class PyMyFloat(PyBase):
def __cinit__(self, double val):
self.thisptr = <void *>(new MyFloat(val))
def __dealloc__(self):
del self.thisptr
def run():
a = PyMyInt(-1)
print(a.is_poitive())
a.add_two()
print(a.is_poitive())
b = PyMyFloat(-2.0)
print(b.is_poitive())
b.add_two()
print(b.is_poitive())
template<typename T>
class Base {
T value;
Base(T val) : value(val) {}
void add_two() {
this->value *= 2;
}
bool is_positive() {
return this->value >= 0;
}
};
class MyInt : public Base<int> {
MyInt(int val) : Base(val) {}
};
class MyFloat : public Base<double> {
MyFloat(double val) : Base(val) {}
}
from distutils.core import setup
from Cython.Build import cythonize
setup(
ext_modules = cythonize("_myheader.pyx", gdb_debug=True)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment