How to pass a 2d array from Python to C?

Dan Shorla Ki

I'm trying to pass a 2d array from Python to C, using ctypes. The array dtype is uint16. I wrote a simple code just to understand how it works:

C:

#include <stdint.h>

__declspec(dllexport) uint16_t Test(uint16_t **arr)
{
     return (arr[5][5]);
}

Python:

import numpy as np
from ctypes import cdll
import ctypes
from numpy.ctypeslib import ndpointer

_p = ndpointer(dtype=np.uint16, ndim=2, shape=(10, 10), flags='C')
mydll = cdll.LoadLibrary("mydll.dll")
_func = mydll.Test
_func.argtypes = [_p]
_func.restypes = ctypes.c_uint16

data = np.empty([10, 10], dtype=np.uint16)
data[5, 5] = 5
print(_func(data))

I get OSError: access violation reading 0xFFFFFFFFFFFFFFFFFFFFFFF what am I doing wrong and how do I fix it?

CristiFati

Listing [SciPy.Docs]: C-Types Foreign Function Interface (numpy.ctypeslib) (and [Python 3.Docs]: ctypes - A foreign function library for Python just in case).

This is a exactly like [SO]: Calling C function in Python through ctypes, but function returns incorrect value (@CristiFati's answer) (a duplicate), it just happens to also involve NumPy.
In other words, you have Undefined Behavior, as argtypes must be CTypes types (not NumPy).

Below is a modified version of the your code, that works.

dll00.c:

#include <stdint.h>

#if defined(_WIN32)
#  define DLL00_EXPORT_API __declspec(dllexport)
#else
#  define DLL00_EXPORT_API
#endif


#if defined(__cplusplus)
extern "C" {
#endif

DLL00_EXPORT_API uint16_t dll00Func00(uint16_t **ppArr);

#if defined(__cplusplus)
}
#endif


uint16_t dll00Func00(uint16_t **ppArr) {
    return ppArr[5][5];
}

code00.py:

#!/usr/bin/env python3

import sys
import ctypes as ct
import numpy as np


DLL_NAME = "./dll00.dll"


def main():
    UI16Ptr = ct.POINTER(ct.c_uint16)
    UI16PtrPtr = ct.POINTER(UI16Ptr)

    dll00 = ct.CDLL(DLL_NAME)
    dll00Func00 = dll00.dll00Func00
    dll00Func00.argtypes = [UI16PtrPtr]
    dll00Func00.restype = ct.c_uint16


    dim0 = 10
    dim1 = 10
    np_arr_2d = np.empty([dim0, dim1], dtype=np.uint16)

    np_arr_2d[5][5] = 5
    print(np_arr_2d)

    # The "magic" happens in the following (3) lines of code
    ct_arr = np.ctypeslib.as_ctypes(np_arr_2d)
    UI16PtrArr = UI16Ptr * ct_arr._length_
    ct_ptr = ct.cast(UI16PtrArr(*(ct.cast(row, UI16Ptr) for row in ct_arr)), UI16PtrPtr)
    res = dll00Func00(ct_ptr)

    print("\n{0:s} returned: {1:d}".format(dll00Func00.__name__, res))


if __name__ == "__main__":
    print("Python {0:s} {1:d}bit on {2:s}\n".format(" ".join(item.strip() for item in sys.version.split("\n")), 64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    print("NumPy: {0:s}\n".format(np.version.version))
    main()
    print("\nDone.")

Output:

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q058727931]> sopr.bat
*** Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ***

[prompt]> "c:\Install\x86\Microsoft\Visual Studio Community\2017\VC\Auxiliary\Build\vcvarsall.bat" x64
**********************************************************************
** Visual Studio 2017 Developer Command Prompt v15.9.17
** Copyright (c) 2017 Microsoft Corporation
**********************************************************************
[vcvarsall.bat] Environment initialized for: 'x64'

[prompt]> dir /b
code00.py
dll00.c

[prompt]> cl /nologo /DDLL dll00.c  /link /NOLOGO /DLL /OUT:dll00.dll
dll00.c
   Creating library dll00.lib and object dll00.exp

[prompt]> dir /b
code00.py
dll00.c
dll00.dll
dll00.exp
dll00.lib
dll00.obj

[prompt]> "e:\Work\Dev\VEnvs\py_064_03.07.03_test0\Scripts\python.exe" code00.py
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] 64bit on win32

NumPy: 1.16.2

[[19760  5277   632     0 32464  5280   632     0   111   114]
 [  107    92    68   101   118    92    86    69   110   118]
 [  115    92   112   121    95    48    54    52    95    48]
 [   51    46    48    55    46    48    51    95   116   101]
 [  115   116    48    92   108   105    98    92   115   105]
 [  116   101    45   112    97     5   107    97   103   101]
 [  115    92   110   117   109   112   121    92   116   101]
 [  115   116   105   110   103    92    95   112   114   105]
 [  118    97   116   101    92   110   111   115   101   116]
 [  101   115   116   101   114    46   112   121     0     0]]

dll00Func00 returned: 5

Done.

The explanation for all those funky conversions can be found at [SO]: C++ & Python: Pass and return a 2D double pointer array from python to c++ (@CristiFati's answer) (and the referenced [SO]: Problems with passing and getting arrays for a C function using ctypes (@CristiFati's answer)).

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Pass 2d array in function - return 2d array from a function in C

分類Dev

How to succesfully pass a 2D array to a function?

分類Dev

How to send a 2D array of floats from javascript to python with flask

分類Dev

How to pass 2D Vector from Rust to Fortran with FFI?

分類Dev

How to display value of 2D Array to QML from C++, using Repeater and GridView

分類Dev

Is it possible to slice a column from 2d array in C

分類Dev

How to input a 2D array in Keras-Python?

分類Dev

How to add elements in a 2D array in Python

分類Dev

How to Convert a String to 2d array in Python?

分類Dev

How to print a 2d character array C++

分類Dev

How can I fully reallocate a 2D array in C?

分類Dev

How to sort strings in an 2D array in C

分類Dev

How to delete this 2d dynamic array in c++

分類Dev

How can i pass a 2d array to JTable in Netbeans efficiently?

分類Dev

Explain how it's possible to allocate and free memory for a 2d array in C with just these 2 lines:

分類Dev

Counting occurrence of non-specified values from 2d array in Python

分類Dev

C language 2d array fill diagonal with numbers from 1 to n

分類Dev

Minimum value on a 2d array python

分類Dev

Pass 2d array as argument to a function using numpy and swig

分類Dev

2d dynamic int array in c

分類Dev

c ++ print / build 2d array

分類Dev

Pointer to 2D Array Argument (C)

分類Dev

How do I read from/write to a binary file in 2D Array form?

分類Dev

How to pass or declare array members in c?

分類Dev

How do I change the dimension of an image from 3D matrix to 2D matrix in python?

分類Dev

How do I declare a 2d array in C++ using new?

分類Dev

How do I check the neighbors of the cells around me in a 2D array (C++)?

分類Dev

C - How can I print random word inside game board (2d array)?

分類Dev

How to display the individual elements of two identical columns inside a 2D array in C

Related 関連記事

  1. 1

    Pass 2d array in function - return 2d array from a function in C

  2. 2

    How to succesfully pass a 2D array to a function?

  3. 3

    How to send a 2D array of floats from javascript to python with flask

  4. 4

    How to pass 2D Vector from Rust to Fortran with FFI?

  5. 5

    How to display value of 2D Array to QML from C++, using Repeater and GridView

  6. 6

    Is it possible to slice a column from 2d array in C

  7. 7

    How to input a 2D array in Keras-Python?

  8. 8

    How to add elements in a 2D array in Python

  9. 9

    How to Convert a String to 2d array in Python?

  10. 10

    How to print a 2d character array C++

  11. 11

    How can I fully reallocate a 2D array in C?

  12. 12

    How to sort strings in an 2D array in C

  13. 13

    How to delete this 2d dynamic array in c++

  14. 14

    How can i pass a 2d array to JTable in Netbeans efficiently?

  15. 15

    Explain how it's possible to allocate and free memory for a 2d array in C with just these 2 lines:

  16. 16

    Counting occurrence of non-specified values from 2d array in Python

  17. 17

    C language 2d array fill diagonal with numbers from 1 to n

  18. 18

    Minimum value on a 2d array python

  19. 19

    Pass 2d array as argument to a function using numpy and swig

  20. 20

    2d dynamic int array in c

  21. 21

    c ++ print / build 2d array

  22. 22

    Pointer to 2D Array Argument (C)

  23. 23

    How do I read from/write to a binary file in 2D Array form?

  24. 24

    How to pass or declare array members in c?

  25. 25

    How do I change the dimension of an image from 3D matrix to 2D matrix in python?

  26. 26

    How do I declare a 2d array in C++ using new?

  27. 27

    How do I check the neighbors of the cells around me in a 2D array (C++)?

  28. 28

    C - How can I print random word inside game board (2d array)?

  29. 29

    How to display the individual elements of two identical columns inside a 2D array in C

ホットタグ

アーカイブ