python 调用C的DLL案例

Posted hahanonym.

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 调用C的DLL案例相关的知识,希望对你有一定的参考价值。

前言: python不能直接调用C++只能调用纯C的DLL

此处案例是python模仿opencv的cv2包,但是用c的DLL调用

 

import os
import csv
import time
import ctypes
from ctypes import *
opencv = CDLL("opencv_world310.dll")


class
IplTileInfo(Structure): _fields_ = [] class IplROI(Structure): _fields_ =[ (coi, c_int), (xOffset, c_int), (yOffset, c_int), (width, c_int), (height, c_int) ] class IplImage(Structure): def __repr__(self): res = [] for field in self._fields_: if field[0] in [imageData, imageDataOrigin]: continue res.append(%s=%s % (field[0], repr(getattr(self, field[0])))) return self.__class__.__name__ + ( + ,.join(res) + ) IplImage._fields_ = [ ("nSize",c_int), ("ID",c_int), ("nChannels",c_int), ("alphaChannel",c_int), ("depth",c_int), ("dataOrder",c_int), ("origin",c_int), ("align",c_int), ("width",c_int), ("height",c_int), ("imageSize",c_int), ("widthStep",c_int), ("BorderMode",c_int*4), ("BorderConst",c_int*4), ("colorModel",c_char*4), ("channelSeq",c_char*4), ("imageData",c_void_p), ("imageDataOrigin",c_char_p), ("imageId",c_void_p), ("roi", POINTER(IplROI)), ("maskROI", POINTER(IplImage)), ("tileInfo", POINTER(IplTileInfo))] loadimageFunc=opencv.cvLoadImage loadimageFunc.argtypes =[c_char_p,c_int] loadimageFunc.restype = POINTER(IplImage) cvimage = loadimageFunc(mpath,2).contents pt=POINTER(c_char) data=ctypes.cast(cvimage.imageData,pt) # 这里的转换非常重要

等同于

import os
import csv
import time
import cv2   #python opencv
import ctypes
from cv2 import *
from ctypes import *   

cvimage = cv2.imread(mpath, cv2.IMREAD_ANYDEPTH)
data=cvimage.ctypes.data_as(ctypes.POINTER(ctypes.c_char))

 

以上是关于python 调用C的DLL案例的主要内容,如果未能解决你的问题,请参考以下文章

如何在 C#/Python 中从 DLL 调用函数

python怎么调用c#的dll

C++ DLL 返回从 Python 调用的指针

创建 可以被python调用的 dll

linux 下的动态库制作 以及在python 中如何调用 c 函数库

从 Python 调用自定义的 C++ dll