从linux可执行文件调用函数



我有这样的python代码:

import svmlight
training_data = __import__('data').train0
test_data = __import__('data').test0
model = svmlight.learn(training_data, type='classification', verbosity=0)
svmlight.write_model(model, 'my_model.dat')
predictions = svmlight.classify(model, test_data)

现在我有了linux可执行文件svmlight_classify,上面的代码和所有函数都在这个可执行文件中。此可执行文件是使用make命令从c代码创建的。

我可以从svmlight_classify可执行文件中直接调用classify()函数吗?

不,我不认为可以直接调用可执行文件中的函数,但可以调用共享库中的函数。您似乎可以访问C源代码,因此应该能够构建这样的共享库:

$ gcc -c -fPIC -o svmlight_classify.o svmlight_classify.c
$ gcc -shared -Wl,-soname,libsvmlight_classify.so -o libsvmlight_classify.so  svmlight_classify.o

这将生成一个名为libsvmlight_classify.so的共享库。现在您可以使用ctypes:加载和调用它的函数

from ctypes import cdll
lib = cdll.LoadLibrary('./libsvmlight_classify.so')
lib.classify()

也许它会比上面更复杂。例如,可能有一些参数需要传递给类型比int、string等更复杂的lib.classify()。如果没有函数原型,我们无法提供建议,但以上通常是您需要做的。

您可以使用ctypes标准模块从DLL调用C函数。

import ctypes
dll = ctypes.CDLL('your.dll') # or 'your.exe'
python_int_returned = dll.YourFunc(ctypes.c_int(3)).value

ctypes.CDLL也可以为可执行文件创建(现在已选中)。我没有检查它的调用函数。无论如何,您需要用extern "C"语句在C++代码中声明C函数,因为C++编译器默认情况下会为C++函数在二进制文件中添加一些"下划线"前缀和后缀(extern "C"会将其关闭)。

复杂的数据通常被传输到C代码作为内存指针(ctypes.POINTER可能很有用)。

最新更新