2011-03-23 135 views
0

我想從使用ctypes的Python調用C++函數add_two_U。功能add_two_U在C++頭文件中定義爲:如何使用沒有輸入參數的ctypes調用函數?

extern ExternalInputs_add_two add_two_U; 

結構ExternalInputs_add_two在頭文件中定義爲:

typedef struct { 
    int32_T Input;      /* '<Root>/Input' */ 
    int32_T Input1;      /* '<Root>/Input1' */ 
} ExternalInputs_add_two; 

功能add_two_initialize我在下面我的Python代碼中調用被定義在頭文件爲:

extern void add_two_initialize(boolean_T firstTime); 

我的Python代碼:

import sys 
from ctypes import * 

class ModelInput(Structure): 
    _fields_ = [("Input", c_int), 
       ("Input1", c_int)] 

#define the functions  
initiateModel = cdll.add_two_win32.add_two_initialize 
U_Model = cdll.add_two_win32.add_two_U 


# define the pointers to the functions 
initiateModel.restype = c_void_p 
U_Model.restype = c_void_p 

#initialize the model with value of 1 
print "\n\nInitialize" 
errMsg = initiateModel(1) 
print "initateModel reports:", errMsg 

#Initialize the structure and get the pointer. 
test_input = ModelInput(1,2) 
input_ptr = pointer(test_input) 

我想通過變量U_Model在python代碼中調用函數add_two_U。請注意,頭文件中此函數沒有任何輸入參數,並使用頭文件中的結構來獲取輸入數據。

我有以下2個問題:

  1. 如何設置在我的Python代碼結構ExternalInputs_add_two結構將數據傳遞到add_two_U功能?

  2. 如何在Python代碼中通過U_Model引用無參數add_two_U的dll函數?如果我使用Python語句來調用函數:

    result = U_Model() 
    

    我得到以下錯誤:

    WindowsError: exception: access violation reading 0xFFFFFFFF 
    

我搜索上線的答案,但沒有找到一個在頭文件中初始化結構並調用沒有參數的函數的示例。

請注意,在我的Python代碼中,由於此函數具有輸入參數,因此我可以調用函數add_two_initialize thru initModel而無錯誤。

回答

1

add_two_U不是一個函數,它是一個導出的值。您需要使用in_dll

請參閱Accessing values exported from dlls

+0

@斯科特我從你的另一個問題看,這似乎是你的答案。請你可以這樣標記它,點擊這個答案旁邊的勾號使它變綠。請閱讀有關所有細節的常見問題解答。 – 2011-03-25 13:42:00

0

David,

謝謝你回答我的第一個問題。我將我的Python代碼更改爲:

#Comment out this line. add_two_U is not a function 
#U_Model = cdll.add_two_win32.add_two_U 

#Get the output pointer from add_two_U 
output = POINTER(ModelInput) 
results = output.in_dll(cdll.add_two_win32,"add_two_U") 

print "got results", results.contents() 

此代碼有效。我仍然無法弄清楚我的第一個問題的答案:如何設置從Python代碼的頭文件中初始化ExternalInputs_add_two結構。

我搜查了ctypes文檔,找不到函數或示例如何執行此操作。我意識到它可能在文檔中。

+0

此空間僅供解答您的問題。您應該編輯您的原始問題以添加其他信息。 – 2011-03-25 01:11:10

相關問題