【发布时间】:2019-07-20 03:47:22
【问题描述】:
我有以下 C 代码,我将从 python 脚本中使用。
这只是一个自动生成的大型库的摘录,很遗憾,我无法更改。在这里,我只是想将结构元素打印到控制台以演示出了什么问题。
// CFunc.h
#include <stdio.h>
typedef struct
{
int npar;
struct
{
int id;
int value;
} params[10];
} Data_t;
void Cfunc( const Data_t * d);
// CFunc.c
#include "CFunc.h"
void Cfunc( const Data_t * d)
{
int inpar = 0;
int maxnpar = 0;
printf("%d:\n", d->npar);
maxnpar = d->npar;
inpar=0;
while (maxnpar > inpar)
{
printf(" %d: %08x %08x\n", inpar, d->params[inpar].id, *(int*)&d->params[inpar].value);
inpar++;
}
}
它被编译并链接到一个共享库:
gcc -fPIC -c CFunc.c -o CFunc.o
gcc -shared -lrt -Wl,-soname,libCFunc.so.1 -o libCFunc.so CFunc.o
所以我使用 ctypes 做了以下实现:
from ctypes import *
lib = CDLL('./libCFunc.so')
class Data_2(Structure):
pass
class Data_t(Structure):
def __init__(self, list):
self.npar = len(list)
self.params = (Data_2 * self.npar)(*list)
Data_2._fields_ = [
('id', c_int),
('value', c_int),
]
Data_t._fields_ = [
('npar', c_int),
('params', POINTER(Data_2)),
]
def pyFunc(d):
lib.Cfunc.argtypes = (POINTER(Data_t),)
lib.Cfunc(byref(d))
return
所以我从给定元组列表中初始化结构,在本例中只有 2 个并调用 C 函数来查看其输出。
paramlist = (
( 0x050000000, 0x00000000 ),
( 0x050000001, 0x447a0000 ) )
temp = Data_t(paramlist)
pyFunc(temp)
很遗憾输出不符合预期:
2:
0: 00000000 79948ef0
1: 00007fe5 00000000
任何想法我错过了什么?
【问题讨论】:
-
关于:
typedef struct { int npar; struct { int id; int value; } params[10]; } Data_t;1) 始终在每个结构上使用“标签”名称,因为这是大多数调试器用来访问结构中各个字段的方法。 2)为了灵活性,将结构的定义与结构的typedef分开 -
我发布的代码只是一个更复杂库的示例,您的顾虑已涵盖...谢谢您的评论。
标签: python c shared-libraries ctypes