问题描述
使用 pybind11,嵌入解释器并从 C++ 调用 Python 函数相对容易。但是,我不知道如何将 Python 成员函数添加到 C++ 类中。
到目前为止我尝试过的:
- 创建一个 C++ 类
public class RNAndroidNotificationListener extends NotificationListenerService { private static final String TAG = "RNAndroidNotificationListener"; @SuppressLint("LongLogTag") @Override public void onNotificationPosted(StatusBarNotification sbn) { Notification notification = sbn.getNotification(); Log.e("Checking Notification","Checking Notification"+ String.valueOf(sbn)); if (notification == null || notification.extras == null) return; String app = sbn.getPackageName(); boolean isDefault = isDefaultDialer(getApplicationContext(),app); if (isDefault) { if (app == null) app = "UnkNown"; CharSequence titleChars = notification.extras.getCharSequence(Notification.EXTRA_TITLE); CharSequence textChars = notification.extras.getCharSequence(Notification.EXTRA_TEXT); if (titleChars == null || textChars == null) return; String title = titleChars.toString(); String text = textChars.toString(); if (text == null || text == "" || title == null || title == "") return; Log.d(TAG,"Notification received: " + app + " | " + title + " | " + text); WritableMap params = Arguments.createMap(); params.putString("app",app); params.putString("title",title); params.putString("text",text); RNAndroidNotificationListenerModule.sendEvent("notificationReceived",params); }else{ Log.e("Else","Not an Incoming Call Notifcation"); return; } }
- 创建一个包装这个类的
HelloWorld
- 将此模块导入 Python 模块,该模块将成员函数添加到
PYBIND11_EMbedDED_MODULE
- 在
HelloWorld
本身中导入该模块
所以在 C++ 方面我有:
HelloWorld
在 Python 方面 (class HelloWorld
{
public:
void run() const
{
py::scoped_interpreter guard{};
auto backend = py::module_::import("backend");
// Todo: call HelloWorld._run()
}
char const *msg() const
{ return "Hello,World!"; }
};
PYBIND11_EMbedDED_MODULE(frontend,m)
{
py::class_<HelloWorld>(m,"HelloWorld")
.def_static("msg",&HelloWorld::msg);
}
)
backend.py
但是我现在如何从 C++ 调用 from frontend import HelloWorld
HelloWorld._run = lambda self: print(self.msg())
?这个设置有意义吗?我们的想法是使用不同的 Python 后端扩展现有的 C++,以便可以快速组合在一起并在运行时进行交换。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)