2015-12-14 65 views
1

我用Python編寫的測試腳本使用ctypes的ctypes - Beginnerctypes的Python的動態函數調用

我有一個函數列表和相應的共享對象名稱來調用C函數,需要調用這些函數動態使用python腳本。

雖然我用它直接調用Python腳本中的函數名稱,但它工作得很好,並在終端上打印「hello world」!

的Python腳本:

import ctypes 
import os 

sharedObjectPath = (os.getcwd() + "/" + "sharedObject.so") 

test = ctypes.CDLL(sharedObjectPath) 
test.printHello() 

的C代碼:

#include < stdio.h> 

void printHello(void); 

void printHello() 
{ 
    printf("hello world\n"); 
} 

然而,它試圖使用一個變量來加載函數名引發錯誤

Python腳本:(動態函數調用)

import ctypes 
import os 

sharedObjectPath = (os.getcwd() + "/" + "sharedObject.so") 

test = ctypes.CDLL(sharedObjectPath) 
fName = "printHello()" 
test.fName 

錯誤: 「完整路徑」 /sharedObject.so:未定義的符號:FNAME

任何幫助和建議深表感謝!謝謝!

回答

1

要使用它的名字作爲一個字符串調用的函數,你這能做到這一點

...  
fName = "printHello" 
test[fName]() 

所以函數名(減去())被用於索引模塊對象後,它的調用。

+0

非常感謝保羅,它解決了這個問題!感謝您的幫助 – cas

+0

沒有probs。如果你願意,隨時接受&upvote。 –