Advanced F2PY usages

Adding self-written functions to F2PY generated modules

可以使用usercodepymethoddef语句(它们必须在python > 模块块)。例如,以下签名文件spam.pyf

!    -*- f90 -*-
python module spam
    usercode '''
  static char doc_spam_system[] = "Execute a shell command.";
  static PyObject *spam_system(PyObject *self, PyObject *args)
  {
    char *command;
    int sts;

    if (!PyArg_ParseTuple(args, "s", &command))
        return NULL;
    sts = system(command);
    return Py_BuildValue("i", sts);
  }
    '''
    pymethoddef '''
    {"system",  spam_system, METH_VARARGS, doc_spam_system},
    '''
end python module spam

包装C库函数system()

f2py -c spam.pyf

在Python中:

>>> import spam
>>> status = spam.system('whoami')
pearu
>> status = spam.system('blah')
sh: line 1: blah: command not found

Modifying the dictionary of a F2PY generated module

以下示例说明如何将用户定义的变量添加到F2PY生成的扩展模块。给定以下签名文件

!    -*- f90 -*-
python module var
  usercode '''
    int BAR = 5;
  '''
  interface
    usercode '''
      PyDict_SetItemString(d,"BAR",PyInt_FromLong(BAR));
    '''
  end interface
end python module

编译为f2py -c var.pyf

Notice that the second usercode statement must be defined inside an interface block and where the module dictionary is available through the variable d (see f2py var.pyf-generated varmodule.c for additional details).

在Python中:

>>> import var
>>> var.BAR
5