python调用c/c++方式示例(修改整理)


Python是解释性语言, 底层就是用c实现的, 所以用python调用C是很容易的, 下面就总结一下各种调用的方法, 给出例子, 所有例子都在ubuntu9.10, python2.6下试过.

 

1. Python 调用 C (base)

想在python中调用c函数, 如这儿的fact

#include <Python.h>

int fact(int n)
{
  if (n <= 1)
    return 1;
  else
    return n * fact(n - 1);
}

PyObject* wrap_fact(PyObject* self, PyObject* args)
{
  int n, result;

  if (! PyArg_ParseTuple(args, "i:fact", &n))
    return NULL;
  result = fact(n);
  return Py_BuildValue("i", result);
}

static PyMethodDef exampleMethods[] =
{
  {"fact", wrap_fact, METH_VARARGS, "Caculate N!"},
  {NULL, NULL}
};

void initexample()
{
  PyObject* m;
  m = Py_InitModule("example", exampleMethods);
}



 

把这段代码存为wrapper.c, 编成so库,

gcc -fPIC wrapper.c -o example.so -shared  -I/usr/include/python2.6 -I/usr/lib/python2.6/config

 

然后在有此so库的目录, 进入python, 可以如下使用

import example

example.fact(4)


 

2. Python 调用 C++ (base)

在python中调用C++类成员函数, 如下调用TestFact类中的fact函数,

#include <Python.h>

class TestFact{
    public:
    TestFact(){};
    ~TestFact(){};
    int fact(int n);
};

int TestFact::fact(int n)
{
  if (n <= 1)
    return 1;
  else
    return n * (n - 1);
}

int fact(int n)
{
    TestFact t;
    return t.fact(n);
}

PyObject* wrap_fact(PyObject* self, PyObject* args)
{
  int n, result;

  if (! PyArg_ParseTuple(args, "i:fact", &n))
    return NULL;
  result = fact(n);
  return Py_BuildValue("i", result);
}

static PyMethodDef exampleMethods[] =
{
  {"fact", wrap_fact, METH_VARARGS, "Caculate N!"},
  {NULL, NULL}
};

extern "C"             //不加会导致找不到initexample
void initexample()
{
  PyObject* m;
  m = Py_InitModule("example", exampleMethods);
}


 

把这段代码存为wrapper.cpp, 编成so库,

g++ -fPIC wrapper.cpp -o example.so -shared -I/usr/include/python2.6 -I/usr/lib/python2.6/config

 

然后在有此so库的目录, 进入python, 可以如下使用

import example

example.fact(4)

 

3. Python 调用 C++ (Boost.Python)

Boost库是非常强大的库, 其中的python库可以用来封装c++被python调用, 功能比较强大, 不但可以封装函数还能封装类, 类成员.

http://dev.gameres.com/Program/Abstract/Building%20Hybrid%20Systems%20with%20Boost_Python.CHN.by.JERRY.htm

首先在ubuntu下安装boost.python, apt-get install libboost-python-dev

#include <boost/python.hpp>
char const* greet()
{
   return "hello, world";
}

BOOST_PYTHON_MODULE(hello)
{
    using namespace boost::python;
    def("greet", greet);
}


把代码存为hello.cpp, 编译成so库

g++ hello.cpp -o hello.so -shared -I/usr/include/python2.5 -I/usr/lib/python2.5/config -lboost_python-gcc42-mt-1_34_1

 

此处python路径设为你的python路径, 并且必须加-lboost_python-gcc42-mt-1_34_1, 这个库名不一定是这个, 去/user/lib查

 

然后在有此so库的目录, 进入python, 可以如下使用

>>> import hello
>>> hello.greet()
'hello, world'


 

4. python 调用 c++ (ctypes)

ctypes is an advanced ffi (Foreign Function Interface) packagefor Python 2.3 and higher. In Python 2.5 it is alreadyincluded.

ctypes allows to call functions in dlls/shared libraries and hasextensive facilities to create, access and manipulate simple andcomplicated C data types in Python - in other words: wraplibraries in pure Python. It is even possible to implement Ccallback functions in pure Python.

http://python.net/crew/theller/ctypes/

 

#include <Python.h>

class TestFact{
    public:
    TestFact(){};
    ~TestFact(){};
    int fact(int n);
};

int TestFact::fact(int n)
{
  if (n <= 1)
    return 1;
  else
    return n * (n - 1);
}

extern "C"
int fact(int n)
{
    TestFact t;
    return t.fact(n);
}


将代码存为wrapper.cpp不用写python接口封装, 直接编译成so库,

g++ -fPIC wrapper.cpp -o example.so -shared -I/usr/include/python2.6 -I/usr/lib/python2.6/config

 

进入python, 可以如下使用

>>> import ctypes
>>> pdll = ctypes.CDLL('/home/ubuntu/tmp/example.so')
>>> pdll.fact(4)
12



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的示例代码,演示如何在Windows系统上实现Python调用C++,以及C++调用PythonPython调用C++示例代码: ```python # test.py import ctypes # 加载C++编译的DLL mydll = ctypes.cdll.LoadLibrary("mydll.dll") # 调用C++函数 result = mydll.add(1, 2) print(result) ``` C++编写的DLL示例代码: ```cpp // mydll.cpp #include <iostream> // 导出函数 extern "C" __declspec(dllexport) int add(int a, int b) { std::cout << "C++ function called." << std::endl; return a + b; } ``` 使用Visual Studio编译上面的C++代码,生成DLL文件mydll.dll。 C++调用Python示例代码: ```cpp // test.cpp #include <Python.h> int main() { Py_Initialize(); // 导入Python模块 PyObject* pModule = PyImport_ImportModule("test"); if (!pModule) { std::cout << "Failed to import module." << std::endl; return 0; } // 导入Python函数 PyObject* pFunc = PyObject_GetAttrString(pModule, "add"); if (!pFunc || !PyCallable_Check(pFunc)) { std::cout << "Failed to import function." << std::endl; return 0; } // 调用Python函数 PyObject* pArgs = PyTuple_New(2); PyTuple_SetItem(pArgs, 0, PyLong_FromLong(1)); PyTuple_SetItem(pArgs, 1, PyLong_FromLong(2)); PyObject* pResult = PyObject_CallObject(pFunc, pArgs); // 获取Python函数返回值 int result = PyLong_AsLong(pResult); std::cout << "Python function called. Result: " << result << std::endl; Py_Finalize(); return 0; } ``` Python代码示例: ```python # test.py def add(a, b): print("Python function called.") return a + b ``` 使用Visual Studio编译上面的C++代码,生成可执行文件test.exe。运行test.exe,即可看到Python函数被调用的结果。 需要注意的是,Python版本和C++编译器版本需要匹配,否则可能会出现兼容性问题。此外,在实际开发中,需要考虑更多的安全和稳定性问题,例如参数型检查、异常处理等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值