是否可以通过引用从python调用C函数?
我是一名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。
如果您编译文件作为共享库或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
我使用-shared编译文件,然后在脚本中使用'my_test_lib = ctypes.cdll.LoadLibrary('/ dir/libfoo.so')'。这个可以吗?? – Piyush 2013-03-19 15:00:35
当我运行我的脚本它显示此错误'追踪(最近呼叫最后): 文件“script1.py”,行18,在
@Piyush:你的shell将'〜'扩展为有效的路径。使用'CDLL(os.path.join(os.path.expanduser('〜'),'auto-test','libsample1.so'))'。 – eryksun 2013-03-20 00:02:08
如何你编译你的C代码?也许你可以使用ctypes。 – HYRY 2013-03-19 13:15:22