pyo3/extensions/custom_type.rs

30 lines
952 B
Rust
Raw Normal View History

#![crate_type = "dylib"]
2016-03-05 00:16:54 +00:00
#![feature(const_fn)]
#[macro_use] extern crate cpython;
use cpython::{Python, PyObject, PyResult, GILProtected};
use cpython::rustobject::{PyRustType, PyRustObject};
2016-03-05 00:16:54 +00:00
use std::cell::RefCell;
static MY_TYPE: GILProtected<RefCell<Option<PyRustType<i32>>>> = GILProtected::new(RefCell::new(None));
py_module_initializer!(custom_type, initcustom_type, PyInit_custom_type, |py, m| {
try!(m.add(py, "__doc__", "Module documentation string"));
2016-03-05 00:16:54 +00:00
*MY_TYPE.get(py).borrow_mut() = Some(try!(m.add_type::<i32>(py, "MyType")
.add("a", py_method!(a()))
.set_new(py_fn!(new(arg: i32)))
2016-03-05 00:16:54 +00:00
.finish()));
Ok(())
});
fn new(py: Python, arg: i32) -> PyResult<PyRustObject<i32>> {
2016-03-05 00:16:54 +00:00
Ok(MY_TYPE.get(py).borrow().as_ref().unwrap().create_instance(py, arg, ()))
}
fn a(py: Python, slf: &PyRustObject<i32>) -> PyResult<PyObject> {
println!("a() was called with self={:?}", slf.get(py));
Ok(py.None())
}