Python 2D array i C using ctypes

后端 未结 1 1543
逝去的感伤
逝去的感伤 2021-01-27 01:00

i\'m trying to use a self written c lib to proces 2d array from python but with little success.

Here is my c code:

CamLibC.c

int TableCam(const i         


        
相关标签:
1条回答
  • 2021-01-27 01:56
    • c_long is the same as c_int, but that is not the problem.

    There are a number of issues:

    • The type of numpy.zeros is default float.
    • In the Python TableCam, A is never modified.
    • In the C TableCam, the 3rd parameter should be int* Array and the elements modified by computing i*y+j. That also agrees with argtypes, which was correct.
    • The numpy array can be coerced to the right ctypes type.

    Corrected code (on Windows, for my testing):

    cam.c

    #include <stdio.h>
    __declspec(dllexport) void TableCam(const int x, const int y, int *Array)
    {
        int i,j;
        for (i = 0; i < x; i++)
            for (j = 0; j < y; j++)
                Array[i*y+j] = 1;
    }
    

    camlib.py

    import ctypes
    
    _CamLib = ctypes.CDLL('cam')
    _CamLib.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_int)]
    _CamLib.restype = None
    
    def TableCam(A):
        x,y = A.shape
        array = A.ctypes.data_as(ctypes.POINTER(ctypes.c_int))
        _CamLib.TableCam(x,y,array)
    

    test.py

    import camlib
    import numpy as np
    
    Anum = np.zeros((3,3),dtype=np.int)
    print('Start:')
    print(Anum)
    camlib.TableCam(Anum)
    print('Ended:')
    print(Anum)
    

    Output

    Start:
    [[0 0 0]
     [0 0 0]
     [0 0 0]]
    Ended:
    [[1 1 1]
     [1 1 1]
     [1 1 1]]
    
    0 讨论(0)
提交回复
热议问题