سؤال

I would like to know if it was possible to add a native method to a Python class without using SWIG or other framework.

I dive into the Python C Api but I don't manage to see the appropriate approach.

I guess I should have an init method that load the existing module and add a method to it :

PyMODINIT_FUNC
PyInit_lambert(void)
{
    PyObject* m;

    m = PyImport_ImportModule("lambert");

    /* Some code to attach method */

    return m;
}

Could someone give me some tips ?

هل كانت مفيدة؟

المحلول

If simplicity is a figure of merit, it's hard to beat the ctypes module. It lets you write the Python-C interface in Python, rather than C. In my experience, it's much easier than writing a Python extension. I suppose there's some overhead, so if this will be called in an inner loop, you may see performance issues.

In the past I've just rewritten the inner most loop in C.

Then, you can subclass in plain old Python.

from some_module import SomeClass

import ctypes

my_c_func = do_the_ctypes_stuff() # see ctypes doc (linked above)

class WrappedClass(SomeClass):
    def added_method(self, *args, **kwargs):
        cargs = my_process_py_args(*args, **kwargs)
        cret = my_c_func(*cargs)
        my_apply_c_result(self, *cret)
        return my_make_py_result(self, *cret)

My suggestion is to write plain Python and plain C, and don't try to get too fancy with the interface.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top