How do I use a macro defined in another crate?

。_饼干妹妹 提交于 2020-02-04 05:46:06

问题


I've seen a couple tutorials to create a Python module using the cpython crate but still have errors when building:

extern crate cpython;

use cpython::{PyObject, PyResult, Python, PyTuple, PyDict, ToPyObject, PythonObject};

fn add_two(py: Python, args: &PyTuple, _: Option<&PyDict>) -> PyResult<PyObject> {
    match args.as_slice() {
        [ref a_obj, ref b_obj] => {
            let a = a_obj.extract::<i32>(py).unwrap();
            let b = b_obj.extract::<i32>(py).unwrap();
            let mut acc:i32 = 0;

            for _ in 0..1000 {
                acc += a + b;
            }

            Ok(acc.to_py_object(py).into_object())
        },
        _ => Ok(py.None())
    }
}

py_module_initializer!(example, |py, module| {
    try!(module.add(py, "add_two", py_fn!(add_two)));
    Ok(())
});

I get:

error: macro undefined: 'py_module_initializer!'

Where do I get it? I am using Rust 1.12.


UPD

  1. Need to add #[macro_use] (as in answers)
  2. For other errors - see examples here

回答1:


You probably need to declare cpython as follows:

#[macro_use] extern crate cpython;

To be able to use cpython's macros. You can consult the example in its docs.




回答2:


You must add the #[macro_use] attribute on the extern crate declaration to ask the compiler to bring the macros exported by the crate into your crate's namespace.

#[macro_use]
extern crate cpython;


来源:https://stackoverflow.com/questions/39945901/how-do-i-use-a-macro-defined-in-another-crate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!