python调用dll

https://www.cnblogs.com/night-ride-depart/p/4907613.html

python源码

# 调用ctpes 组件
from ctypes import *
if __name__ == '__main__':
    # 调用需要调用的dll, dll中的方法都可以使用了
    dll= CDLL("DemoDll.dll")

    # python中默认类型是int,可以直接调用 returnAddInt方法
    print dll.returnAddInt(1,2)

    # float类型demo 多参
    #设置返回类型
    dll.returnAddFloat.restype=c_float
    #设置参数类型(多参可以用小括号表示)
    dll.returnAddFloat.argtypes=(c_float,c_float)
    
    print dll.returnAddFloat(1.2,2.3)

    #float类型demo 单参
    dll.returnFloat.restype = c_float
    # 单参数需要使用中括号
    dll.returnFloat.argtypes = [c_float]
    print dll.returnFloat(1.2)

    # char类型demo
    dll.returnChar.restype = c_char
    dll.returnChar.argtypes = [c_char]
    print dll.returnChar("x")

    # char* 类型demo
    dll.returnPoint.restype = c_char_p
    dll.returnPoint.argtypes = [c_char_p]
    print dll.returnPoint("xyz")

    # 结构体类型 demo
    # 定义类名 
    class MyStruct(Structure):
        #定义参数名与参数类型
        _fields_=[('value',c_int)]
    dll.returnMyStruct.restype =MyStruct
    dll.returnMyStruct.argtypes = [c_int]
    s=dll.returnMyStruct(2)
    print s.value

    # int* demo
    dll.getIntP.restype=c_int
    #定义类型为指针类型
    dll.getIntP.argtypes=[POINTER(c_int)]
    # 建立 int* 实例
    a = c_int(1)
    c = POINTER(c_int)(a)
    print dll.getIntP(c)


c

#include "DemoDll.h"
char returnChar(char a) {
    return a;
}
int returnAddInt(int a, int b) {
    return a + b;
}
float returnAddFloat(float a, float b) {
    return a + b;
}
float returnFloat(float a) {
    return a;
}
char* returnPoint(char * s) {
    printf("helloWorld");
    return s;
}
struct MyStruct
{
    int value;
};
struct MyStruct returnMyStruct(int a) {
    struct MyStruct m;
    m.value = a;
    return m;
}
int getIntP(int* i) {
    return i;
}

.h

#pragma once
#include 
__declspec(dllexport) char returnChar(char a);
__declspec(dllexport) int returnAddInt(int a, int b);
__declspec(dllexport) float returnFloat(float a);
__declspec(dllexport) float returnAddFloat(float a, float b);
__declspec(dllexport) char* returnPoint(char * s);
__declspec(dllexport) struct MyStruct returnMyStruct(int a);
__declspec(dllexport) int getIntP(int* i);

你可能感兴趣的:(python调用dll)