小编don*_*dak的帖子

从Python访问C声明的嵌套结构

我在C中静态声明了一个大型结构,但我需要使用相同的数据在Python中进行一些分析.我宁愿不将这些数据重新复制到Python中以避免错误,有没有办法直接在Python中访问(只读)这些数据?我看过"ctypes"和SWIG,他们似乎都没有提供我正在寻找的东西......

例如,我有:

/*.h文件*/

typedef struct
{
  double data[10];
} NestedStruct;


typedef struct
{
   NestedStruct array[10];
} MyStruct;
Run Code Online (Sandbox Code Playgroud)

/*.c文件*/

MyStruct the_data_i_want = 
{
  {0},
  {
   {1,2,3,4}
  },
  {0},
};
Run Code Online (Sandbox Code Playgroud)

理想情况下,我想要的东西可以让我把它变成python并通过the_data_i_want.array[1].data[2]类似的东西访问它.有什么想法吗?从我能够编译/导入从我的.c文件创建的.so这个意义上来说,我已经开始"工作",但是我无法通过cvars访问它.也许有另一种方式?看起来这不应该那么难......


实际上,我想通了.我添加这个是因为我的声誉不允许我在8小时内回答我自己的问题,因为我不想在8小时内记住,我现在就加上它.我确信有一个很好的理由,我不明白.

弄清楚了.

我将我的.c文件编译成一个库:

然后,我使用类型来定义一个保存数据的python类:

from ctypes import *

class NestedStruct(Structure):
    _fields_ = [("data", c_double*10)]

class MyStruct(Structure):
    _fields_ = [("array", NestedStruct*10)]
Run Code Online (Sandbox Code Playgroud)

然后,我将共享库加载到python中:

my_lib = cdll.LoadLibrary("my_lib.so")
Run Code Online (Sandbox Code Playgroud)

然后,我使用"in_dll"方法来获取数据:

the_data_i_want = MyStruct.in_dll(my_lib, "the_data_i_want")
Run Code Online (Sandbox Code Playgroud)

然后,我可以访问它,就像它是C. the_data_i_want.array[1].data[2]

注意我可能在这里稍微搞砸了语法,因为我的实际数据结构嵌套了3个级别,我想简化这里的插图.

c python swig ctypes

8
推荐指数
1
解决办法
1324
查看次数

标签 统计

c ×1

ctypes ×1

python ×1

swig ×1