2013-03-19 168 views
2

我是一名Python初學者,我需要測試一個被引用調用的C函數。是否可以通過引用從python調用C函數?

這裏是我的C文件:myfile.c文件

#include<stdio.h> 

int my_function(int *x) 
{ 
int A; 
printf("enter value of A"); 
scanf("%d",&A); 
*x = 10 * A; // this sets the value to the address x is referencing to 
return 0; 
} 

現在, 我的Python腳本應該調用創建my_function(),並傳遞參數,這樣我可以檢查和驗證結果。

類似:

result = self.loaded_class.my_function(addressOf(some_variable))

self.assertEqual(some_variable,10)

這可能嗎?我怎麼能做到這一點。 而我正在爲Python自動測試編寫腳本,而不是使用交互式python。

+1

如何你編譯你的C代碼?也許你可以使用ctypes。 – HYRY 2013-03-19 13:15:22

回答

2

如果您編譯文件作爲共享庫或DLL(我不知道該怎麼做),你可以使用ctypes這樣的(假設它是在這個例子中一個DLL):

import ctypes as ct 

mylib = ct.cdll.myfile 
c_int = ct.c_int(0) 
mylib.my_function(ct.byref(c_int)) 
print c_int.value 
+0

我使用-shared編譯文件,然後在腳本中使用'my_test_lib = ctypes.cdll.LoadLibrary('/ dir/libfoo.so')'。這個可以嗎?? – Piyush 2013-03-19 15:00:35

+0

當我運行我的腳本它顯示此錯誤'追蹤(最近呼叫最後): 文件「script1.py」,行18,在 testlib = ctypes.CDLL('〜/ auto-test/libsample1.so ') 文件「/usr/lib/python2.7/ctypes/__init__.py」,行365,在__init__中 self._handle = _dlopen(self._name,mode) OSError:〜/ auto-test/libsample1。所以:無法打開共享目標文件:沒有這樣的文件或目錄' – Piyush 2013-03-19 21:02:55

+0

@Piyush:你的shell將'〜'擴展爲有效的路徑。使用'CDLL(os.path.join(os.path.expanduser('〜'),'auto-test','libsample1.so'))'。 – eryksun 2013-03-20 00:02:08

1

你可以編寫一個C語言函數的Python接口,一個簡單的例子是Python doc。但是,如果您只想測試C函數,那麼您可能更適合使用C/C++測試框架,例如Google Test

相關問題