在 Python SWIG 中包装一个 void * 参数 [英] Wrapping a void * argument in Python SWIG

查看:28
本文介绍了在 Python SWIG 中包装一个 void * 参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Python SWIG 包装这个库,它的函数如下所示:

I am wrapping this lib with Python SWIG that has a function looking like this:

int set_option(Foo *foo, const char *name, void *value);

在库中 const char *name 映射到我可以访问的类型:int, char *, <代码>字符**.

In the lib const char *name is mapped to a type that I have access to look up: int, char *, char **.

默认生成的包装器代码只接受一个包装好的void *(自然).

The wrapper code generated by default accepts only a wrapped void * (naturally).

让包装方法接受任何 Python 对象作为参数,并在我自己的 C 代码中进行类型检查和 Python 到 C 的转换的最佳方法是什么?

What is the best way to make the wrapped method accept any Python object as argument, and do the type checking, and Python to C conversion in my own C code?

我的猜测是某种类型的地图,但可惜我无法弄清楚.

My guess would be some kind of type map, but alas I cannot figure it out.

@Goodies

In [12]: lib.set_option(foo, "option", "value")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-4ccf706b5c50> in <module>()
----> 1 lib.set_option(foo, "option", "value")

TypeError: in method 'set_option', argument 3 of type 'void *'

推荐答案

如果您只想将 PyObject 传递给使用 %extend 的内容,您可以修改您的内容已经得到并简单地写下以下内容:

If you just want to pass a PyObject to something using %extend you can modify what you've got and simply write the following:

%extend Foo {
    int set_option(const char *name, PyObject *value) {
            // Here value is now a PyObject *, so work with that.
            // $self is Foo *foo
            return 0;
    }
};

不需要类型映射,这个函数现在可以接受任何 Python 输入.你用它做什么取决于你,如果你保留对象,你需要增加引用计数.

There's no need for a typemap and this function now accepts any Python input. What you do with it is up to you and if you retain the object you'll need increase the reference count.

这篇关于在 Python SWIG 中包装一个 void * 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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