zoukankan      html  css  js  c++  java
  • 使用python的内置ctypes模块与c、c++写的dll进行交互

    • 调用C编写的动态链接库

    • 代码示例
    from ctypes import *
    dll = CDLL("add.dll")#加载cdecl的dll。另外加载stdcall的dll的方式是WinDLL("dllpath")
    sum=dll.Add(1, 102)


    • 若参数为指针
    p=1
    sum=dll.sub(2, byref(p))#通过库中的byref关键字来实现


    • 若参数为结构体

    C代码如下:

    typedef struct
    {
        char words[10];
    }keywords;
    
    typedef struct
    {
        keywords *kws;
        unsigned int len;
    }outStruct;
    
    extern "C"int __declspec(dllexport) test(outStruct *o);
    
    int test(outStruct *o)
    {
        unsigned int i = 4;
        o->kws = (keywords *)malloc(sizeof(unsigned char) * 10 * i);
        strcpy(o->kws[0].words, "The First Data");
        strcpy(o->kws[1].words, "The Second Data");
        o->len = i;
        return 1;
    }



    Python代码如下:

    class keywords(Structure):
        _fields_ = [('words', c_char *10),]
    
    class outStruct(Structure):
        _fields_ = [('kws', POINTER(keywords)),('len', c_int),]
    
    o = outStruct()
    dll.test(byref(o))
    
    print (o.kws[0].words)
    print (o.kws[1].words)
    print (o.len)





    • 调用Windows API

    #导入ctypes模块
    from ctypes import *
    windll.user32.MessageBoxW(0, '内容!', '标题', 0)
    
    #也可以用以下方式为API函数建立个别名后再进行调用
    MessageBox = windll.user32.MessageBoxW
    MessageBox(0, '内容!', '标题', 0)

    运行结果预览



  • 相关阅读:
    c++ 为自定义类添加stl遍历器风格的遍历方式
    C++ 生成随机数
    c/c++ 函数说明以及技巧总结
    XSLT 教程
    C# 高效过滤DataTable 中重复数据方法
    xml获取指定节点的路径
    TreeView控件
    推荐一些C#相关的网站、资源和书籍
    C#多线程操作
    C#二进制序列化
  • 原文地址:https://www.cnblogs.com/beta2013/p/3377323.html
Copyright © 2011-2022 走看看