实际调用方法与调用c语言的动态l库类似,也有两种方法,本文仅描述其中一种方式:
第一步,制作c++动态库:代码如下:
#include <Python.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
class TestSum{
public:
TestSum(){};
~TestSum(){};
int sum(int a,int b);
};
int TestSum::sum(int a,int b)
{
return a+b;
}
int sum(int a,int b)
{
TestSum test;
return test.sum(a,b);
}
PyObject* wrap_sum1(PyObject* self, PyObject* args)
{
int result;
int a=1;
int b=2;
if (! PyArg_ParseTuple(args, "ii", &a,&b))
return NULL;
printf("\n -- a=%d,b=%d \n",a,b);
result = sum(a,b);
return Py_BuildValue("i", result);
}
static PyMethodDef exampleMethods1[] =
{
{"sum1", wrap_sum1, METH_VARARGS, "Caculate N!"},
{NULL, NULL}
};
extern "C" #---------注意这块表示很重要,如果没有,python调用动态库会出问题;
void initexample()
{
PyObject* m;
m = Py_InitModule("example", exampleMethods1);
}
第二步编译:g++ -fPIC example.cpp -o example.so -shared -I/usr/include/python2.7 -I/usr/lib/python2.7/config
第三步实验:
[root@host150 callfun_c++]# python
Python 2.7.5 (default, Aug 4 2017, 00:39:18)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import example
>>> dir(example)
['__doc__', '__file__', '__name__', '__package__', 'sum1']
>>> example.sum1(8,9)
-- a=8,b=9
17
为什么c++可库中加入extern "C"
大家可以做个实验,然后上网自己搜索;
实验:使用上面的动态库,在linuxshell执行 nm example.so | grep initexample得到如下结果
[root@host150 callfun_c++]# nm example.so | grep initexample
0000000000000c11 T initexample
如果在程序中将extern "C"去掉,编译个动态库,再次执行nm example.so | grep initexample得到如下结果
[root@host150 callfun_c++]# nm example1.so | grep initexample
0000000000000c11 T _Z11initexamplev
这个就是符号表相关的知识;具体上上网查找详细说明;