meta:

  • name: keywords content: 使用 numpy.distutils 模块
  • name: description content: numpy.distutils 是NumPy扩展标准Python distutils的一部分,用于处理Fortran源代码和F2PY签名文件…

高级F2PY用法

将自编写函数添加到F2PY生成的模块

可以使用 usercodepymethoddef 语句在签名文件中定义自编的Python C / API函数(它们必须在 python模块 块中使用)。 例如,以下签名文件spam.pyf

  1. ! -*- f90 -*-
  2. python module spam
  3. usercode '''
  4. static char doc_spam_system[] = "Execute a shell command.";
  5. static PyObject *spam_system(PyObject *self, PyObject *args)
  6. {
  7. char *command;
  8. int sts;
  9. if (!PyArg_ParseTuple(args, "s", &command))
  10. return NULL;
  11. sts = system(command);
  12. return Py_BuildValue("i", sts);
  13. }
  14. '''
  15. pymethoddef '''
  16. {"system", spam_system, METH_VARARGS, doc_spam_system},
  17. '''
  18. end python module spam

包装C库函数system()

  1. f2py -c spam.pyf

在Python中:

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

修改F2PY生成模块的字典

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

  1. ! -*- f90 -*-
  2. python module var
  3. usercode '''
  4. int BAR = 5;
  5. '''
  6. interface
  7. usercode '''
  8. PyDict_SetItemString(d,"BAR",PyInt_FromLong(BAR));
  9. '''
  10. end interface
  11. end python module

将其编译为:f2py -c var.pyf

请注意,必须在 interface(接口) 块内定义第二个 usercode 语句,并且通过变量 d 可以获得模块字典(有关其他详细信息,请参阅f2py var.pyf 生成的 varmodule.c)。

在Python中:

  1. >>> import var
  2. >>> var.BAR
  3. 5