python调用c++动态库练习

实际调用方法与调用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


这个就是符号表相关的知识;具体上上网查找详细说明;













  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值