5

Developing a module (.pyd) for Python in free pascal is fairly easy, see Developing Python Modules with Pascal. But if I want to interface with numpy, this is not that easy. When using C to interface with numpy, you have to add #include <numpy/arrayobject.h> to the code, and also call import_array(); in the initialization function.

Is there a way to interface with numpy in pascal?

EDIT1

As mentioned in the comments under @wilberforce answer, the import_array function which is defined in the header files just imports multiarray.pyd module into the current interpreter and does some checking. It is easily translated into pascal and it works.

The numpy C-API functions are not present initially in pythonXX.dll, so they can't be linked statically. Static or dynamic linking with multiarray.pyd is not working for me.

So the updated question is: Is there a way to access the C-API functions embedded in multiarray.pyd from code which is not C?

hdrz
  • 461
  • 6
  • 12
  • Just found out about delphi's 'delayed' keyword, which lets you load a function from external library on demand (d2010+). It could work in this situation. I'm on free pascal only, so until it is implemented... – hdrz Dec 10 '13 at 13:51

1 Answers1

1

Treat the numpy library like any other C library from Pascal's point of view - you need to include the header and declare import_array as an external cdecl function.

This guide covers the details.

You already need to have done some of this in order to have written a Python extension module so your Pascal code can use the Python API functions to interact with Python objects. You can see this in the cdecl; external PythonLib; modifiers in the example you link to. It's possible this wasn't clear while you were doing it.

babbageclunk
  • 8,523
  • 1
  • 33
  • 37
  • 1
    The problems are that (1) `import_array` is declared in `arrayobject.h` and it's includes, (2) none of the numpy functions are declared in the python dll, and (3) using `multiarray.pyd` for the external functions doesn't work. – hdrz Nov 14 '13 at 13:02
  • `import_array` is mapped to the function `_import_array`, which essentialy imports the numpy module. Maybe if I rewrite this function in pascal it will work. – hdrz Nov 14 '13 at 13:10
  • Oh, I see - they define a static _import_array in a generated header file - that's nasty! (Although I'm sure they have their reasons.) – babbageclunk Nov 14 '13 at 14:57
  • It looks like you would have to reimplement it in Pascal - it should be a fairly mechanical translation. You could even contribute it back to numpy as a header-type file that gets generated in the same way as https://github.com/numpy/numpy/blob/master/numpy/core/code_generators/generate_numpy_api.py – babbageclunk Nov 14 '13 at 15:13