2016-02-11 84 views
0

我必須整合python與外部so庫。不幸的是,C代碼使用全局變量SimpleTest_Y(結構),我需要訪問它以修改值。如何通過Python和ctype訪問C全局變量結構

這裏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 

initialize方法的調用蟒作品,但是當我試圖訪問SimpleTest_Y.Out1我得到以下錯誤:

print SimpleTest_Y.Out1 

AttributeError: '_FuncPtr' object has not attribute 'Out1'

我想我不能夠訪問外部C庫定義的全局變量...

注意:這是一個不正常的結構

+0

你給的頭文件的例子是不完整的,並且將無法編譯。 – b4hand

+0

已更新但它由simulink生成 – venergiac

+2

這些字段在SimpleTest.h中都是double,但是你的ctypes代碼使用'c_float'而不是'c_double'。 – eryksun

回答

2

您需要使用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