2013-03-19 105 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

相关问题