Skip to content

Instantly share code, notes, and snippets.

@bjodah
Last active October 21, 2016 18:29
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/001633712d2531f20a74ab975bb08e62 to your computer and use it in GitHub Desktop.
Save bjodah/001633712d2531f20a74ab975bb08e62 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8; mode: cython -*-
# distutils: language = c++
from struct_ex cimport OutVectors
cdef class PyClass:
cdef OutVectors *thisptr
def __cinit__(self, int x=1, int y=1):
self.thisptr = new OutVectors(x, y)
def __dealloc__(self):
del self.thisptr
def sum(self):
return self.thisptr.x + self.thisptr.y
def square_approximate_area(double area):
cdef int side = round(area**0.5)
return PyClass(side, side)
def make_ext(modname, pyxfilename):
from Cython.Build import cythonize
return cythonize([pyxfilename])[0]
#pragma once
namespace examp {
struct OutVectors { // names beginning with "_" are reserved C/C++
int x, y;
OutVectors(int x_=1, int y_=1) : x(x_), y(y_) {}
};
}
# -*- coding: utf-8; mode: cython -*-
cdef extern from "struct_ex.hpp" namespace "examp":
cdef cppclass OutVectors:
int x, y
OutVectors(int, int)
import pyximport
pyximport.install()
from my import PyClass, square_approximate_area
def main():
pc = PyClass(2, 3)
if pc.sum() == 5:
print("Success!")
else:
print("Failure!")
sq = square_approximate_area(25.0)
if sq.sum() == 10:
print("Success!")
else:
print("Failure!")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment