【问题标题】:How to access to C global variable structure by Python and ctype [duplicate]如何通过 Python 和 ctype 访问 C 全局变量结构
【发布时间】:2016-02-11 18:06:52
【问题描述】:

我必须将 python 与外部 so 库集成。不幸的是,C 代码使用了一个全局变量 SimpleTest_Y(结构),我需要访问它才能修改值。

这里是 C 代码

SimpleTest.c 文件

#include "SimpleTest.h"

/* External inputs (root inport signals with auto storage) */
ExtU_SimpleTest_T SimpleTest_U;

/* External outputs (root outports fed by signals with auto storage) */
ExtY_SimpleTest_T SimpleTest_Y;


/* Model initialize function */
void SimpleTest_initialize(void)
{
  /* external outputs */
  SimpleTest_Y.Out1 = 3.0;
}

SimpleTest.h 文件

#ifndef SimpleTest_COMMON_INCLUDES_
# define SimpleTest_COMMON_INCLUDES_
#include <stddef.h>
#include <string.h>
#endif                                 

/* External inputs (root inport signals with auto storage) */
typedef struct {
  double In1;                          /* '<Root>/In1' */
  double In2;                          /* '<Root>/In2' */
} ExtU_SimpleTest_T;

/* External outputs (root outports fed by signals with auto storage) */
typedef struct {
  double Out1;                         /* '<Root>/Out1' */
} ExtY_SimpleTest_T;


/* External inputs (root inport signals with auto storage) */
extern ExtU_SimpleTest_T SimpleTest_U;

/* External outputs (root outports fed by signals with auto storage) */
extern ExtY_SimpleTest_T SimpleTest_Y;

/* Model entry point functions */
extern void SimpleTest_initialize(void);

python 包装器

import ctypes

class Inp(ctypes.Structure):
   _fields_ = [('In1', ctypes.c_float),
               ('In2', ctypes.c_float)]

class Out(ctypes.Structure):
   _fields_ = [('Out1', ctypes.c_float)]               


myLib = ctypes.CDLL('./SimpleTest.so')

#Initialize
SimpleTest_initialize = myLib.SimpleTest_initialize
SimpleTest_initialize()



#Output
SimpleTest_Y = myLib.SimpleTest_Y
SimpleTest_Y.restype = ctypes.POINTER(Out)

#print type(SimpleTest_Y)
print SimpleTest_Y.Out1

初始化方法的python调用有效,但是当我尝试访问SimpleTest_Y.Out1时出现以下错误:

print SimpleTest_Y.Out1

AttributeError: '_FuncPtr' 对象没有属性 'Out1'

我认为我无法访问在外部 C 库上定义的全局变量...

注意:这是一个结构,不是普通的 var

【问题讨论】:

  • 你给出的头文件示例不完整,不会编译。
  • 已更新,但它是由 simulink 生成的
  • SimpleTest.h中的字段都是double,但是你的ctypes代码使用c_float而不是c_double

标签: python c ctypes simulink


【解决方案1】:

您需要使用in_dll 方法来访问全局变量。

这行得通:

import ctypes

class Inp(ctypes.Structure):
   _fields_ = [('In1', ctypes.c_float),
               ('In2', ctypes.c_float)]

class Out(ctypes.Structure):
   _fields_ = [('Out1', ctypes.c_float)]

myLib = ctypes.CDLL('./SimpleTest.so')

SimpleTest_initialize = myLib.SimpleTest_initialize
SimpleTest_initialize()

SimpleTest_Y = Out.in_dll(myLib, 'SimpleTest_Y')

print SimpleTest_Y.Out1

【讨论】:

    猜你喜欢
    • 2010-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多