因为算法效率问题所以要在python中调用C,
先写一个C函数:
test.cpp
# include<stdio.h>
# include <stdlib.h> //atoi
# include <string.h> //strlen
# include <unistd.h> //gethostname()
# include <stdint.h> //uint64_t
int add(int a,int b){
printf("this is from C dll");
return a+b;
}
编译 :
gcc -c -fPIC test.cpp
gcc -shared test.o -o test.so
然后在python中调用sum函数:
mylib.py
from ctypes import *
libc=CDLL("test.so")
libc.sum(2,2)
运行:
python mylib.py
出错:******can not find symbol sum
发现是因为c++编译后的文件会把函数名改名(为了实现重载功能)
用extern “C”声明后,就会使用c的方式进行编译,编译后的文件中仍然是定义的函数名
所以只要讲c库中的代码改为:
# include<stdio.h>
# include <stdlib.h> //atoi
# include <string.h> //strlen
# include <unistd.h> //gethostname()
# include <stdint.h> //uint64_t
extern "C"{
int sum(int,int);
}
int sum(int a,int b){
printf("this is from C dll");
return a+b;
}