2

Is it possible to create a Python Array in C using the C-API?

If so how do I do this?

Is arraymodule.c the right place to be looking in the CPython source?

If I was using numpy I'd do this https://docs.scipy.org/doc/numpy/user/c-info.how-to-extend.html#creating-a-brand-new-ndarray but I can't use numpy for this particular project.

shuttle87
  • 15,466
  • 11
  • 77
  • 106
  • Have you thought about using `Cython`? It wouldn't written in `c` directly, but might solve your actual problem, depending on what it is. http://docs.cython.org/en/latest/ – James Schinner Jan 21 '18 at 12:26
  • I have used Cython in the past, I'm just wondering if the very specific case of creating an Array from the CAPI is possible. What got me thinking about this is I'm currently creating a cross compilation utility for Python extensions and bringing in other dependencies is undesirable. My problem I was trying to solve was to pass around a a contiguous chunk of memory without a copy, there's other ways to do that of course, but this question is driven by curiosity about this very specific case and not what I was initially trying to solve. – shuttle87 Jan 21 '18 at 12:52
  • 1
    I don't think the array API is exported specifically, but you can call the Python interface from C if that's any help (I assume you know how to do that and are looking for something more direct...). Unfortunately all the initialization functions involve making a copy of existing Python data which might be a little inefficient. – DavidW Jan 21 '18 at 15:24
  • what type of data you want share with python land using arraymodule? – georgexsh Jan 23 '18 at 07:46
  • @georgexsh I have some C++ `std::array` and `std::vectors` and I was hoping to conveniently expose those by creating `array.array` objects straight out of the C-API without having to copy the underlying memory. I suspect I will have to wrap these in array types on the Python side. – shuttle87 Jan 23 '18 at 08:56
  • 1
    I think `array.array` objects always own their memory so that this would unavoidably require a copy. What you could do is create a class that [implements](http://cython.readthedocs.io/en/latest/src/userguide/buffer.html#a-matrix-class) the [python buffer protocol](https://docs.python.org/3/c-api/buffer.html) while not making a copy. (The example linked in Cython but you can do it with the C API) – DavidW Jan 24 '18 at 18:29

0 Answers0