python调用c中函数

使用讯飞的语音识别api时,由于想将使用python写的 vad与该api结合使用,所以选择使用讯飞使用c编写的 linux sdk。将api作为一个函数,在python中调用。使用到python的包 ctypes https://docs.python.org/2/library/ctypes.html#return-types

环境:
python3.5
centos

实例

编写文件 lib.c

int multiply(int num1, int num2)
{
    return num1 * num2;
}

把 test.c 文件编成动态链接库

gcc -c -fPIC lib.c
gcc -shared lib.o -o lib.so

编写调用上面 multiply 函数的python程序 test.py

from ctypes import *
import os
lib = cdll.LoadLibrary(os.getcwd() + '/lib.so')
print(lib.multiply(2, 2))

说明: lib.c 与 test.py放在同一个目录下
执行上面的文件 test.py : python3 test.py
输出值: 4

以上lib.c 中的函数的输入参数都为 int, 函数返回值也为 int。

更进一步

函数返回值

如果有 lib2.c 文件,其函数返回值为 字符串, 无输入参数:

char* out()
{
    char value[5] = "abcd";
    return value;
}

编译成动态链接库, python文件中调用,lib2.py

from ctypes import *
import os
lib2 = cdll.LoadLibrary(os.getcwd() + '/lib2.so')
print(lib2.out())

执行输出值: 1406100496
这个值还是个 int 类型。这个结果明显不对。

参考 ctypes 文档知,默认情况下传给c函数数据尽量转换为 相应的 ctypes 类型

对于函数输入参数:
15.17.1.5. Calling functions, continued

Since these types are mutable, their value can also be changed afterwards:
As has been mentioned before, all Python types except integers, strings, and unicode strings have to be wrapped in their corresponding ctypes  type, so that they can be converted to the required C data type

对于函数返回值:
参考 15.17.1.8. Return types

By default functions are assumed to return the C int type. Other return types can be specified by setting the restype attribute of the function object.

更在

将 lib2.py 改为如下:
(数据类型对应关系c_char_p — char * (NUL terminated) – string or None, 更多的参考ctypes官网文档)

from ctypes import *
import os
lib2 = cdll.LoadLibrary(os.getcwd() + '/lib2.so')
lib2.out.restype = c_char_p
print(lib2.out())              

函数输入

编写 lib3.c

#include
char* cat(char* arg)
{
    char value[10] = "abcd";
    strcat(value, arg);
    return value;
}

lib3.py 文件:

from ctypes import *
import os
lib3 = cdll.LoadLibrary(os.getcwd() + '/lib3.so')
lib3.cat.restype = c_char_p
arg = "1234".encode("utf-8")
result = lib3.cat(c_char_p(arg))
print(result)   

执行 lib3.py 输出正确结果: b’abcd1234’

参考:
PYTHON调用C语言函数
http://coolshell.cn/articles/671.html

ctypes — A foreign function library for Python
https://docs.python.org/2/library/ctypes.html#return-types

你可能感兴趣的:(python,c)