从C函数构建PyObject *? [英] Build a PyObject* from a C function?

查看:141
本文介绍了从C函数构建PyObject *?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将Python嵌入正在制作的C ++库中.我希望用户能够以函数指针PyObject* (fpFunc*)(PyObject*,PyObject*);的形式传递C函数,以便可以在嵌入式Python中使用这些函数.

I am embedding Python in a C++ library which I am making. I would like users to be able to pass C functions in the form of function pointers PyObject* (fpFunc*)(PyObject*,PyObject*); so that I can use those functions in the embedded Python.

所以我有一个函数指针,我知道可以使用PyMethodDef结构将该函数作为模块的方法放置,并将其传递给Py_InitModule("module", ModMethods);,从而获得一个PyObject* module,我可以轻松地获取函数来自.

So I have a function pointer and I know that it is possible to put this function as a module's method using a PyMethodDef struct and passing it to Py_InitModule("module", ModMethods); and thus obtaining a PyObject* module which I can easily grab functions from.

但是,我真正希望能够在不每次都重新创建另一个模块的情况下即时创建此功能.

But, what I would really appreciate is to be able to create this function on the fly without necessarily recreating another module each time.

我已经研究了Python文档和一些Python标头,以考虑一种骇人听闻的方式来实现此目的,但并没有真正的成功...但是我想知道是否还有一种更常规的方式来做到这一点.

I have looked into the Python docs, and some of the Python headers to think about a hacky way of doing this without real success... but I'm wondering if's there's a more conventional way of doing this.

据我了解,每个功能都属于一个模块,甚至是__builtin__,所以我想我至少需要一个模块.

From what I understood, every function belongs to a module, even __builtin__, so I guess I would require at least on module.

关于如何实现这一目标的任何想法?

Any idea on how to achieve this?

推荐答案

找到了它.尽管它不在文档中,并且在源代码中也不太明确.

Found it. Though it's not in the docs and it's hardly explicit in the source.

PyObject* (*fpFunc)(PyObject*,PyObject*) = someFunction;
PyMethodDef methd = {"methd",fpFunc,METH_VARARGS,"A new function"};
PyObject* name = PyString_FromString(methd.ml_name);
PyObject* pyfoo = PyCFunction_NewEx(&methd,NULL,name);
Py_DECREF(name);

有效.我可以像通常调用Python函数对象一样调用函数.

It works. I can call the function like I normally would call a Python function object.

如果您很好奇,我在文档中发现的所有内容都是关于Py_InitModule4和加载模块的,所以我去检查了Python的源代码,并找到了关于PyCFunction的内容,然后我在文档中四处张望,但我无法没有找到有关PyCFunction_NewEx的任何信息,因此我不得不检查源以确保它与我的想法一样.

If you're curious, all I found in the doc was about Py_InitModule4 and loading modules, so I went to check Python's source, and found out about PyCFunction, then I looked around in the doc but I couldn't find anything about PyCFunction_NewEx, so I had to check the source to make sure it was as I thought.

这篇关于从C函数构建PyObject *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆