如何通过Python和ctype访问C全局变量结构 [英] How to access to C global variable structure by Python and ctype
问题描述
我必须将python与外部so库集成。不幸的是,C代码使用了全局变量 SimpleTest_Y
(结构),我需要访问它才能修改值。
I have to integrate python with external so library. Unfortunately, the C code uses a global variable SimpleTest_Y
(structure) and I need to access it in order to modify the value(s).
此处是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文件
SimpleTest.h file
#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 wrapper
python wrapper
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
initialize方法的python调用有效,但是当我尝试访问<$ c时$ c> SimpleTest_Y.Out1 我收到以下错误:
The python invocation of the initialize method works, but when I try to access to SimpleTest_Y.Out1
I get the following error:
print SimpleTest_Y.Out1
AttributeError: _ FuncPtr对象没有属性te'Out1'
AttributeError: '_FuncPtr' object has not attribute 'Out1'
我想我无法访问在外部C库中定义的全局变量...
I think I'm not able to access to global var defined on external C library...
注意:这是一个非常规变量的结构
推荐答案
您需要使用 in_dll
方法来访问全局变量。
You need to use the in_dll
method to access a global variable.
此方法有效:
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
这篇关于如何通过Python和ctype访问C全局变量结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!