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

2019-02-20 11:28:16 +08:00
 css3

各位大佬,有 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

3160 次点击
所在节点    Python
7 条回复
ysc3839
2019-02-20 12:07:40 +08:00
1. 试试直接用 int
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: 我也是查找资料才找到类似的, 以上代码可运行成功
aihimmel
2019-02-20 13:54:25 +08:00
css3
2019-02-20 14:25:49 +08:00
@dinjufen 我这个是 unsigned char 的二级指针,你的例子好像跟我这个不太一样,多谢
css3
2019-02-20 14:26:11 +08:00
@aihimmel 唉,打不开啊
dinjufen
2019-02-20 16:05:18 +08:00
@css3 我写的是 int 的二级指针,应该替换一下就行了吧
aihimmel
2019-02-20 17:05:21 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/536822

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX