【问题标题】:Calling C function from python using ctypes使用 ctypes 从 python 调用 C 函数
【发布时间】:2014-08-20 14:23:35
【问题描述】:

我有以下 C 代码。我正在尝试使用 ctypes 从 Python 调用此函数:

int add ( int arr []) 
{
    printf("number %d \n",arr[0]);
    arr[0]=1;
    return arr[0];
}

我使用以下代码编译了这个:

gcc -fpic -c test.c 
gcc -shared -o test.so test.o

然后将其放入/usr/local/lib

对此的 Python 调用是:

from ctypes import *

lib = 'test.so'
dll = cdll.LoadLibrary(lib)
IntArray5 = c_int * 5
ia = IntArray5(5, 1, 7, 33, 99)
res = dll.add(ia)
print res

但我总是得到一些像-1365200 这样的大数字。

我也试过了:

dll.add.argtypes=POINTER(c_type_int)

但它不起作用。

【问题讨论】:

    标签: python c call wrapper ctypes


    【解决方案1】:

    请尝试:

    dll = cdll.LoadLibrary('test.so')
    res = dll.add(pointer(c_int(5)))
    print res
    

    【讨论】:

      【解决方案2】:

      尝试围绕它构建:

      lib = 'test.so'
      dll = cdll.LoadLibrary(lib)
      
      dll.add.argtypes=[POINTER(c_int)]
      #                ^^^^^^^^^^^^^^^^
      #         One argument of type `int *̀
      
      dll.add.restype=c_int
      # return type 
      
      res =dll.add((c_int*5)(5,1,7,33,99))
      #            ^^^^^^^^^
      #       cast to an array of 5 int
      
      print res
      

      用 Python 2.7.3 和 2.6.9 测试过

      【讨论】:

        猜你喜欢
        • 2016-02-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-02
        相关资源
        最近更新 更多