通过名称获取对嵌入式 python 函数的 C 引用?

发布于 2024-08-18 02:26:27 字数 258 浏览 2 评论 0原文

假设我有一些包含函数 foo 的嵌入式 python 代码,那么获取对该函数的引用(与 PyObject_CallObject 一起使用)的最佳方法是什么?

一种方法是让某个函数手动或通过使用反射来注册每个函数以及函数名称。这似乎有点矫枉过正。

另一种方法是创建一个“加载器”函数,该函数获取函数名称并返回对该函数的引用。更好,但我仍然必须使用 C 注册加载器函数。

我是否缺少一种更好的方法来执行此操作,无论是否需要编写任何额外的 python 代码?

Assuming I have some embedded python code containing a function foo, what is the best way to get a reference to that function (for use with PyObject_CallObject)?

One way is to have some function register each function along with the function name either manually or through use of reflection. This seems like overkill.

Another way is to create a "loader" function that takes the function name and returns a reference to the function. Better, but I still have to register the loader function with C.

Am I missing a better way to do this with or without having to write any additional python code?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

↙厌世 2024-08-25 02:26:27

阅读文档中有关嵌入 Python 的部分。我猜你有一个包含该函数的模块的引用。
最后有一个示例展示了如何从对象中获取函数引用。

pFunc = PyObject_GetAttrString(pModule, argv[2]);
/* pFunc is a new reference */

if (pFunc && PyCallable_Check(pFunc)) {
    ...
}
Py_XDECREF(pFunc);

Read the section in the documentation about embedding Python. I guess you have a reference to the module containing the function.
At the end there is an example which shows how to get a function reference out of an object.

pFunc = PyObject_GetAttrString(pModule, argv[2]);
/* pFunc is a new reference */

if (pFunc && PyCallable_Check(pFunc)) {
    ...
}
Py_XDECREF(pFunc);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文