gpt4 book ai didi

python - 将 Python 字典转换为 ctypes 结构

转载 作者:太空狗 更新时间:2023-10-30 00:05:23 25 4
gpt4 key购买 nike

我有一个包含以下条目的 Python 字典:

Tmp={'Name1': [10.0, 20.0, 'Title1', 1], 'Name2': [5.0, 25.0, 'Title2', 2]}

我想将其传递给 C 函数,该函数定义为:

struct CA {
char *Keys;
float *Values;
char *Title;
int Index;
};

void myfunc (struct CA *in, int n);

在 Python 方面,我创建了一个等效的 ctypes 结构:

class CA(ctypes.Structure):
_fields_ = [("Keys", ctypes.POINTER(ctypes.c_char_p)),
("Values", ctypes.POINTER(ctypes.c_float)),
("Title", ctypes.POINTER(ctypes.c_char_p)),
("Index", ctypes.c_int)]

并使用以下方法创建了一个 CA 数组:

CAarray = CA * 2

现在我想在一个循环中将 Tmp 分配给 CAarray

k = Tmp.keys()
for (j, _) in enumerate(k):
CAarray[j].Keys = _
CAarray[j].Values = Tmp[_][:2]
CAarray[j].Title = Tmp[_][2]
CAarray[j].Index = Tmp[_][3]

我一直在努力使语法正确,但到目前为止都失败了。帮助。

另外,是否有任何例程/库可以处理 Python 变量和 ctypes 变量之间的相互转换?

最佳答案

我创建了一个测试 DLL 来验证该结构能否正确通过。

#include <stdio.h>

struct CA {
char *Keys;
float *Values;
char *Title;
int Index;
};

__declspec(dllexport) void myfunc (struct CA *in, int n)
{
int i;
for(i = 0; i < n; ++i)
{
printf("%d: Keys = %s\n",i,in[i].Keys);
printf("%d: Values = %f %f\n",i,in[i].Values[0],in[i].Values[1]);
printf("%d: Title = %s\n",i,in[i].Title);
printf("%d: Index = %d\n",i,in[i].Index);
}
}

我是这样调用它的:

#!python3
from ctypes import *

class CA(Structure):
_fields_ = [('Keys',c_char_p),
('Values',POINTER(c_float)),
('Title',c_char_p),
('Index',c_int)]

Tmp={'Name1': [10.0, 20.0, 'Title1', 1], 'Name2': [5.0, 25.0, 'Title2', 2]}

# repackage Tmp as a list of CA structures
ca_list = []
for k,v in Tmp.items():
ca = CA()
ca.Keys = k.encode('utf8') # Python 3 strings are Unicode, char* needs a byte string
ca.Values = (c_float*2)(v[0],v[1]) # Interface unclear, how would target function know how many floats?
ca.Title = v[2].encode('utf8')
ca.Index = v[3]
ca_list.append(ca)

# repackage python list of CAs to ctype array of CAs
ca_array = (CA * len(ca_list))(*ca_list)

dll = CDLL('./test')
dll.myfunc.argtypes = POINTER(CA),c_int
dll.myfunc.restype = None

dll.myfunc(ca_array,len(ca_array))

输出:

0: Keys = Name1
0: Values = 10.000000 20.000000
0: Title = Title1
0: Index = 1
1: Keys = Name2
1: Values = 5.000000 25.000000
1: Title = Title2
1: Index = 2

关于python - 将 Python 字典转换为 ctypes 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42506296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com