V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
css3
V2EX  ›  Python

Python 调用 C,结构体中嵌套了枚举该如何创建这种对应的 Python 类?😭😭😭

  •  
  •   css3 · 2019-02-20 11:28:16 +08:00 · 3153 次点击
    这是一个创建于 1863 天前的主题,其中的信息可能已经有所发展或是发生改变。

    各位大佬,有 2 个问题需要请求一下,感激不尽😭

    1、单独的结构体,可以直接用 python 的类来创建,但这结构体里边嵌套了一个枚举,应该怎么创建这种结构体啊

    typedef struct
    {
        AttrType  eType;
        int                 nValue;     
        float               fScore;
    }T_Result;
    
    typedef enum
    {
        A     = 0, 
        B     = 1, 
        C 	  = 2, 
        D     = 3, 
    }AttrType;
    

    2、python 调用 C 函数,遇到二级指针,如何传参数呢?以下我的办法不可用

    // C 函数原型, 伪代码:
    
    A(IF_UINT8 ** A1)
    {
        xx
        return 0;
    }
    
    
    typedef unsigned char       IF_UINT8;
    
    
    # python 调用
    
    dll = CDLL("test.dll")
    
    dll.A.argtypes = [POINTER(POINTER(c_ubyte))]
    
    args= POINTER(c_ubyte)()
    
    dll.A(byref(args))
    
    # 这样报错:OSError: exception: access violation reading 0x0000000000000004
    
    
    7 条回复    2019-02-20 17:05:21 +08:00
    ysc3839
        1
    ysc3839  
       2019-02-20 12:07:40 +08:00 via Android
    1. 试试直接用 int
    2. 需要代码才知道具体该怎么办
    dinjufen
        2
    dinjufen  
       2019-02-20 13:25:21 +08:00
    C 代码:
    // dll1.h

    #pragma once

    #define EXPT __declspec(dllexport)


    extern "C" {
    EXPT void A(int** arg);
    }


    // dll1.cpp

    #include "stdafx.h"
    #include "Dll1.h"

    void A(int** arg) {
    printf("arg = %d", **arg);
    }


    Python 代码:
    from ctypes import cdll
    from ctypes import POINTER, cast
    from ctypes import c_int

    dll = cdll.LoadLibrary("Dll1.dll")

    dll.A.argtypes = [POINTER(POINTER(c_int))]

    p_x = POINTER(c_int)
    List_int = [(5,)]
    List = (c_int*1*1)(*List_int)
    List_p = []
    List_p.append(cast(List[0], p_x))
    p2ci = (p_x*1)(*List_p)

    # 调用
    dll.A(p2ci)


    PS: 我也是查找资料才找到类似的, 以上代码可运行成功
    css3
        4
    css3  
    OP
       2019-02-20 14:25:49 +08:00
    @dinjufen 我这个是 unsigned char 的二级指针,你的例子好像跟我这个不太一样,多谢
    css3
        5
    css3  
    OP
       2019-02-20 14:26:11 +08:00
    @aihimmel 唉,打不开啊
    dinjufen
        6
    dinjufen  
       2019-02-20 16:05:18 +08:00
    @css3 我写的是 int 的二级指针,应该替换一下就行了吧
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   958 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 21:38 · PVG 05:38 · LAX 14:38 · JFK 17:38
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.