1

PyUFunc_FromFuncAndDataを使用して、C関数をコンパイルしてnumpyジェネリック関数を作成するコードがいくつかあります。ufunc を作成するためにいくつかの cython を作成しましたが、配布するつもりであり、ユーザーのコンパイル手順を回避したいので、可能であれば ctypes で実行したいと考えています。

問題は、PyUFunc_FromFuncAndData が PyObject へのポインターを返すことです。Python コードからオブジェクトとして使用することは可能ですか?

基本的に、次の cython コードを python/ctypes に変換できるようにしたいと考えています。

from numpy cimport NPY_DOUBLE
from libc.stdlib cimport malloc, free

cdef extern from "numpy/ufuncobject.h":
    ctypedef void (*PyUFuncGenericFunction) (char **, Py_ssize_t *, Py_ssize_t *, void *)
    object PyUFunc_FromFuncAndData (PyUFuncGenericFunction *, void **, char *, int, int, int, int, char *, char *, int)
    void import_ufunc()

import_ufunc()


cdef class UFuncWrapper:

    cdef readonly object func
    cdef object _llvm_func
    cdef PyUFuncGenericFunction function
    cdef char *types
    cdef bytes name

    def __init__(self, func, ufunc, long long ptr):
        self._llvm_func = ufunc # keep a ref to prevent it from being gced
        cdef int num_args = len(func.args)
        self.types = <char*>malloc(sizeof(char)*(num_args+1))
        self.name = func.name
        cdef int i
        for i in range(num_args+1):
            self.types[i] = NPY_DOUBLE
        self.function = <PyUFuncGenericFunction>ptr
        self.func = PyUFunc_FromFuncAndData(
            &self.function,
            NULL,
            self.types,
            1,  #ntypes
            num_args,
            1,
            -1, # PyUFunc_None,
            self.name,
            self.name,   #FIXME: __doc__
            0)

    def __dealloc__(self):
        free(self.types)

    def __call__(self, *args):
        return self.func(*args)
4

1 に答える 1

3

その関数の restype を ctypes.py_object に設定します。次の例では、python C-API への呼び出しを使用していますが、それ以外でも同じように機能します。

import ctypes
class Foo(object):
    bar='baz'

foo=ctypes.py_object(Foo)
print 'Memory adress of Foo.bar object:',
print ctypes.pythonapi.PyObject_GetAttrString(foo,'bar') # prints the pointer

ctypes.pythonapi.PyObject_GetAttrString.restype = ctypes.py_object

print 'Actual Foo.bar after we set restype correctly:', 
print ctypes.pythonapi.PyObject_GetAttrString(foo,'bar') # prints "baz"
于 2011-03-02T10:40:46.737 に答える