首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >动态c lib.so与python的集成

动态c lib.so与python的集成
EN

Stack Overflow用户
提问于 2013-07-25 07:57:48
回答 1查看 174关注 0票数 3

我试图将用c++编写的共享库集成到已经运行的python应用程序中。为此,我创建了一个简单的.so文件,并试图访问用共享库编写的函数。

代码语言:javascript
复制
from ctypes import *
import cv2 as cv
import numpy as np
print cv.__version__

so= 'ContrastEnhancement.so'
lib = cdll.LoadLibrary(so)

image = cv.imread('python1.jpg')
image_data = np.array(image)

#calling shared lib function here
lib.ContrastStretch(image_data, width ,height, 5,10)
cv.imwrite("python_result.jpg", )

代码语言:javascript
复制
Traceback (most recent call last):
File "test1.py", line 21, in <module>
  lib.ContrastStretch(image_data, width ,height, 5,10)



ctypes.ArgumentError: argument 1: <type 'exceptions.TypeError'>: Don't know how to convert parameter 1

如果我试过像这样

代码语言:javascript
复制
 lib.ContrastStretch(c_uint8(image_data), width ,height, 5,10)
 TypeError: only length-1 arrays can be converted to Python scalars

现在看来,这与共享库无关,而是“如何在python中使用图像数据(数组)”。

谢谢贾维德

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-08-11 21:36:18

问题是ctype不知道共享库中函数的签名。在调用函数之前,您必须让ctype知道它的签名。对于ctype来说,这有点麻烦,因为它有自己的小型语言来完成这个任务。

我建议使用cffi。Cython也是一种选择,但是如果您只是使用cython包装c库,通常会有很多烦人的开销,您必须基本上学习一种全新的语言(cython)。是的,它在语法上类似于python,但是理解和优化cython性能需要在我的经验中实际读取生成的C。

使用cffi (docs:http://cffi.readthedocs.org/en/release-0.7/),您的代码应该如下所示:

代码语言:javascript
复制
import cffi
ffi = cffi.FFI()

# paste the function signature from the library header file
ffi.cdef('int ContrastStretch(double* data, int w0 ,int h0, int wf, int hf)

# open the shared library
C = ffi.dlopen('ContrastEnhancement.so')

img = np.random.randn(10,10)

# get a pointer to the start of the image
img_pointer = ffi.cast('double*', img.ctypes.data)
# call a function defined in the library and declared here with a ffi.cdef call
C.ContrastStretch(img_pointer, img.shape[0], img.shape[1], 5, 10)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17852219

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档