我正在尝试创建Actix,它具有PyO3解释器& Py对象。
问题是,创建python解释器参与者的正确方法是什么?
我认为错误是由演员的特质定义为静态的。https://docs.rs/actix/0.7.4/actix/trait.Actor.html
是否有行为者或上下文中有对象要求生命参数的方式?
锈蚀版本:夜间-2018-09-04,actix版本: 0.7.4
这是当前代码。
extern crate actix;
extern crate actix_web;
extern crate pyo3;
use actix::prelude::*;
use actix_web::{http, server, ws, App, HttpRequest, HttpResponse, Error};
use pyo3::{Python, GILGuard, PyList};
struct WsActor<'a> {
// addr: Addr<PyActor>,
gil: GILGuard,
python: Python<'a>,
pylist: &'a PyList,
}
impl<'a> Actor for WsActor<'a> {
type Context = ws::WebsocketContext<Self>;
}
fn attach_ws_actor(req: &HttpRequest<()>) -> Result<HttpResponse, Error> {
let gil = Python::acquire_gil();
let python = gil.python();
let pylist = PyList::empty(python);
let actor = WsActor {gil, python, pylist};
ws::start(req, actor)
}
fn main() {
let sys = actix::System::new("example");
server::new(move || {
App::new()
.resource("/ws/", |r| r.method(http::Method::GET).f(attach_ws_actor))
}).bind("0.0.0.0:9999")
.unwrap()
.start();
}这段代码不能用这个错误编译。
error[E0478]: lifetime bound not satisfied
--> src/main.rs:15:10
|
15 | impl<'a> Actor for WsActor<'a> {
| ^^^^^
|
note: lifetime parameter instantiated with the lifetime 'a as defined on the impl at 15:6
--> src/main.rs:15:6
|
15 | impl<'a> Actor for WsActor<'a> {
| ^^
= note: but lifetime parameter must outlive the static lifetime发布于 2018-09-17 10:14:38
正如尼古拉所说,您可以将Py<PyList>对象存储在WsActor中。要恢复PyList,您可以再次获取GIL并调用AsPyRef特性的.as_ref(python)方法( Py<T>实现该方法)。一个例子如下:
extern crate actix;
extern crate actix_web;
extern crate pyo3;
use actix::prelude::*;
use actix_web::{http, server, ws, App, HttpRequest, HttpResponse, Error};
use pyo3::{Python, PyList, Py, AsPyRef};
struct WsActor {
// addr: Addr<PyActor>,
pylist: Py<PyList>,
}
impl Actor for WsActor {
type Context = ws::WebsocketContext<Self>;
}
impl StreamHandler<ws::Message, ws::ProtocolError> for WsActor {
fn handle(&mut self, _: ws::Message, _: &mut Self::Context) {
let gil = Python::acquire_gil();
let python = gil.python();
let list = self.pylist.as_ref(python);
println!("{}", list.len());
}
}
fn attach_ws_actor(req: &HttpRequest<()>) -> Result<HttpResponse, Error> {
let gil = Python::acquire_gil();
let python = gil.python();
let pylist = PyList::empty(python);
let actor = WsActor {
pylist: pylist.into()
};
ws::start(req, actor)
}
fn main() {
let sys = actix::System::new("example");
server::new(move || {
App::new()
.resource("/ws/", |r| r.method(http::Method::GET).f(attach_ws_actor))
}).bind("0.0.0.0:9999")
.unwrap()
.start();
}发布于 2018-09-12 06:54:23
演员特质的定义是
pub trait Actor: Sized + 'static { ... }这意味着,你一生的'a必须是'static。
这里有一个小示例
use std::marker::PhantomData;
trait Foo: Sized + 'static {
fn foo();
}
struct Bar<'a> {
_marker: PhantomData<&'a i32>,
}
impl<'a> Foo for Bar<'a> { //not possible
fn foo() {}
}
struct Baz<'a> {
_marker: PhantomData<&'a i32>,
}
impl Foo for Baz<'static> { //possible
fn foo() {}
}https://stackoverflow.com/questions/52288565
复制相似问题